Retrieve data using ajax in asp.net with Json.NET

What is Json.NET Json.NET is a third party library which helps conversion between JSON text and .NET object is using the JsonSerializer. The JsonSerializer converts .NET objects into their JSON equivalent text and back again by mapping the .NET object property names to the JSON property names. It is open source software and free for commercial purpose.

How to install

In Visual Studio, go to Tools Menu -> Choose Library Package Manager -> Package Manager Console. It opens a command window where we need to put the following command to install Newtonsoft.Json.
How to open Nuget Package Manger
Install-Package Newtonsoft.Json:
In Visual Studio, Tools menu -> Manage Nuget Package Manager Solution and type “JSON.NET” to search it online. Here’s the figure:

Json Install

Json Install

WebForm1.aspx


<form id="form1" runat="server">
        <div>
            
        </div>
        <div id="dvCustomers">
            <table id="tblCustomer" cellpadding="2" cellspacing="0" border="1">
                <tr>
                    <th>NAME</th>
                    <th>CITY</th>
                </tr>
                
            </table>
        </div>
    </form>
</pre>
<script type="text/javascript">
$(document).ready(function () {
getData();
});
function getData() {

$.ajax({
type: "POST",
url: "WebForm1.aspx/GetCustomers",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
}
function OnSuccess(response) {
var contact = JSON.parse(response.d);
$.each(contact, function (i, v) {
$("#tblCustomer").append('<tr><td>' + v.Name + '</td><td>' + v.City + '</td> </tr>');
});
}
</script>

WebForm1.cs


[WebMethod]

public static string GetCustomers()
{

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("City",typeof(string)) });
dt.Rows.Add(1, "Bhuwan Maitra", "Kolkata");
dt.Rows.Add(2, "Gursharn Singh", "Dubai");
dt.Rows.Add(3, "Shamikant", "Jamshedpur");
dt.Rows.Add(4, "Hitesh Maity", "Jamshedpur");

DataSet ds = new DataSet("DSTest");
ds.Tables.Add(dt);

return JsonConvert.SerializeObject(dt);
}

Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion and problems if you face – let us know. We’d love to help!

Tags: , , ,