Link to home
Start Free TrialLog in
Avatar of Sirdots
Sirdots

asked on

Display json result in html

I have a method that returns json. Am using mvc 3. How can I write the html part to display my data. Here is my method and my Ajax script



[HttpPost]
        public JsonResult GetAllProducts(string searchName)       
        {
            string myConnect = ConfigurationManager.ConnectionStrings["ConnectSir"].ConnectionString;
            List<Product> prdResults = new List<Product>();
           
            string sqlcmd = @"select * from products where name = @name";
            SqlConnection con = new SqlConnection(myConnect);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = sqlcmd;

            cmd.Parameters.Add("@name", SqlDbType.NVarChar);
            cmd.Parameters["@name"].Value = searchName;
            cmd.Parameters["@name"].Direction = ParameterDirection.Input;
         
            using (con)
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Product newProduct = new Product();
                    newProduct.Id = Convert.ToInt16(reader["Id"]);
                    newProduct.Name = reader["Name"].ToString();
                    newProduct.Description = reader["description"].ToString();
                    newProduct.Price = Convert.ToDecimal(reader["Price"]);
                    newProduct.UnitsInStock = Convert.ToInt16(reader["UnitsInStock"]);
                    prdResults.Add(newProduct);
                }

            }
            //return prdResults;
           return Json(prdResults);
        }

Open in new window

           

<script type="text/javascript">
    $('#btnSearch').click(function () {
        $.ajax({
            url: 'Home/GetAllProducts/',
            type: 'POST',
            dataType: 'json',
            data: { searchName: $('#searchItem').val() } 
        })        
        
    });
    
</script>

Open in new window

SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sirdots
Sirdots

ASKER

I have not been able to get this to work. Do I put all the code on one page?
yes, try the example first let me know if it don't work for you.
do you have the jQUery plugin installed with the right path and did you add the jquery template plugin after?
Avatar of Sirdots

ASKER

Thanks. It is still not working. Here is my code below. Nothing is displayed.

@model IEnumerable<MvcAjax.Models.Product>
                     
<script src="../../Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.loadTemplate-1.2.1.js" type="text/javascript"></script>

<form>
    <div>
        <input type="text" name="search" id="searchItem" />
        <input type="submit"  value="Retrieve" id="btnSearch"/>
    </div>

<div>
&nbsp;
</div>

<script id="productTemplate" type="text/x-jquery-tmpl">
      <tr><td>${ Name }</td><td>${ Description }</td><td>${ Price }</td></tr>
</script>

<script type="text/javascript">
    $('#btnSearch').click(function () {
        $.ajax({
            url: 'Home/GetAllProducts/',
            type: 'POST',
            dataType: 'json',
            data: { searchName: $('#searchItem').val() },
            success: function (json) {
                $('#productTemplate').tmpl(json).appendTo('#myTable');
            }
        })

    });
</script>


<table id="myTable">
<tr><th>NAME</th><th>DESC</th><th>PRICE</th></tr>
</table>


</form>

Open in new window

Avatar of Sirdots

ASKER

And to answer your question Yes I added the jquery version 10 as well as the template.
You should NOT use a submit button else you form will be posting, and you will not have time to see things you do inside your ajax success function

so replace : <input type="submit"  value="Retrieve" id="btnSearch"/>
by : <input type="button"  value="Retrieve" id="btnSearch"/>
Avatar of Sirdots

ASKER

Thanks again. I changed that and I am still having problems on the line below

$('#productTemplate').tmpl(json).appendTo('#myTable');


I got  the error message below.

Microsoft JScript runtime error: Object doesn't support property or method 'tmpl'

What else can i try?
Yes, my bad, it's an other plugin.
Use the following line instead :
$("#myTable").loadTemplate($('#productTemplate'), json);
Avatar of Sirdots

ASKER

Things are looking better. The data is not displayed though. Please see the attached image to see what it is displayed.

${ Name } ${ Description } ${ Price }
sample.PNG
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Sirdots

ASKER

Thanks a million. It works like magic.
Avatar of Sirdots

ASKER

Thanks.