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

AJAXASP.NET

Avatar of undefined
Last Comment
Sirdots

8/22/2022 - Mon
SOLUTION
leakim971

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Sirdots

I have not been able to get this to work. Do I put all the code on one page?
leakim971

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?
ASKER
Sirdots

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

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER
Sirdots

And to answer your question Yes I added the jquery version 10 as well as the template.
leakim971

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"/>
ASKER
Sirdots

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?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
leakim971

Yes, my bad, it's an other plugin.
Use the following line instead :
$("#myTable").loadTemplate($('#productTemplate'), json);
ASKER
Sirdots

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
leakim971

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Sirdots

Thanks a million. It works like magic.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
Sirdots

Thanks.