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

SirdotsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
You may use jQuery.template : https://github.com/codepb/jquery-template
https://github.com/codepb/jquery-template/blob/master/Examples/SimpleExample/example.html

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

Open in new window


<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>

Open in new window


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

Open in new window

0
SirdotsAuthor Commented:
I have not been able to get this to work. Do I put all the code on one page?
0
leakim971PluritechnicianCommented:
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?
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

SirdotsAuthor Commented:
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

0
SirdotsAuthor Commented:
And to answer your question Yes I added the jquery version 10 as well as the template.
0
leakim971PluritechnicianCommented:
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"/>
0
SirdotsAuthor Commented:
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?
0
leakim971PluritechnicianCommented:
Yes, my bad, it's an other plugin.
Use the following line instead :
$("#myTable").loadTemplate($('#productTemplate'), json);
0
SirdotsAuthor Commented:
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
0
leakim971PluritechnicianCommented:
Check example link, line 16 to 18, it should display something with :
<script id="productTemplate" type="text/x-jquery-tmpl">
      <tr><td data-content="Name"></td><td data-content="Description"></td><td data-content="Price"></td></tr>
</script>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
SirdotsAuthor Commented:
Thanks a million. It works like magic.
0
SirdotsAuthor Commented:
Thanks.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
AJAX

From novice to tech pro — start learning today.