Returning JSON data to view in MVC

Below was the code to return data to the view

Code inside controller :

 public class SampleController : Controller
    {

public class Products
        {
            public int ProductId { set; get; }
            public string ProductName { set; get; }
    }

        public JsonResult GetJsonData()
        {
             var list = new List<Products>();
                list.Add(new Products { ProductId = 1, ProductName = “P1” });
             list.Add(new Products { ProductId = 2, ProductName = “P2” });
             list.Add(new Products { ProductId = 3, ProductName = “P3” });
             list.Add(new Products { ProductId = 4, ProductName = “P4” });
             return list;
        }

}

Code inside javascript :

 

    function GetData()
    {
        $.ajax({
            contentType: ‘application/json; charset=utf-8’,
            type: “POST”,
            url: ‘http://localhost:51798/Sample/GetJsonData&#8217;, // Make sure to change the port number here
            dataType: “json”,// Make sure that the datatype is json
            success: function (data) {
        for(var i=0;i<data.length;i++)
        {
                   console.log(data[i]. ProductName);
        }
            }
        });
       }

…..

Thanks,

Lakshman.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s