Handling json data returned from asp net web services

preview_player
Показать описание
Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our YouTube channel. Hope you can help.

In this video we will discuss
2. Consume JSON data returned by the web service using jQuery AJAX

Approach 1 : With Approach 1, the web service code does not change in any way.

We need to add/change the following options of the jquery request object.
1. Add contentType option and set it to application/json; charset=utf-8 to specify that we will be sending a JSON string.
2. Use JSON.stringify() method to convert the data you are sending to the server to a JSON string
3. Change the dataType to json, to specify that you are expecting JSON data from the server
4. Modify the success function to display Name, Gender and Salary property values from the JSON object.

Please note : By defaut, the JSON object returned by the web service has a property d. So to retrieve Name property value, use data.d.Name.

$(document).ready(function () {
$('#btnGetEmployee').click(function () {

var empId = $('#txtId').val();

$.ajax({
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ employeeId: empId }),
dataType: "json",
method: 'post',
success: function (data) {
$('#txtName').val(data.d.Name);
$('#txtGender').val(data.d.Gender);
$('#txtSalary').val(data.d.Salary);
},
error: function (err) {
alert(err);
}
});
});
});

Approach 2 : With Approach 2 both the web service code and the jQuery code need to change.

Modify the ASP.NET web service as shown below to return JSON data

1. Serialize the employee object to JSON string using JavaScriptSerializer and write it to the response stream.
2. Since the method is not returning anything set the return type of the method to void.

namespace Demo
{
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class EmployeeService : System.Web.Services.WebService
{
[WebMethod]
public void GetEmployeeById(int employeeId)
{
Employee employee = new Employee();

string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
cmd.CommandType = CommandType.StoredProcedure;

SqlParameter parameter = new SqlParameter();
parameter.Value = employeeId;

cmd.Parameters.Add(parameter);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
employee.ID = Convert.ToInt32(rdr["Id"]);
employee.Name = rdr["Name"].ToString();
employee.Gender = rdr["Gender"].ToString();
employee.Salary = Convert.ToInt32(rdr["Salary"]);
}
}

JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(employee));
}
}
}

1. contentType option is no longer required, so you may remove it.
2. You don't have to convert the data that you are sending to the server to JSON string, so you may remove JSON.stringify() method
3. The JSON object returned from the server will not have property d, so you don't have to use d on the data object. For example, you can now retrieve Name property simply by using data.Name.
Рекомендации по теме
Комментарии
Автор

Nice content venkat. Clearly understood the ajax capability.

TellaTrix
Автор

I've just found answer to my question in previous video, amazing :D !!

braScene
Автор

Neat and clean content, thank you very much.

jalalshaibany
Автор

Hi kudvenkat.
When I run my web app in local mode, it runs perfect !! but, when deploy to a server, ajax calls does returns any data.
Any property to change in web service ? Thnks.

devve
Автор

thanks Venkat!
would you pass the strong datatype from UI to MVC Action using JQuery:

ruthyayele
Автор

Hi Venkat,
When i tried the second approach i could see the response in Fiddler but it was not getting reflected in the textboxes. I suspect the service is returning string instead of JSON because when i used JSON.parse in the ajax call to convert the response text boxes started getting populated.

success:function(response)
{
var data=JSON.parse(response);
$('#txtName').val(data.Name);
...
...
..
..
}

ashishkalra
Автор

I want to send this to other website, should I?

learningroom
Автор

Could you help me here? I'm using something similiar, bus I have in may WS person's data, like name, birthday, id, weight, but I need to integrate iwht my sistem, which have his car type, car color and car plate.
I how should I integrate them? because, if I need to sort this list, by person name I will need to mix the whole data from the WB with my DB?

CarlosAlbertoBrasil
Автор

I am getting an error like "undefined" when i follow the first approach.Why?

sambireddyannapureddy
Автор

Sir,
I am trying to send the object and getting back the generic list of object in json format back in response.
But In response error function is executed and in in consol.log(data) getting object with extra appended Object {"d":null}
Why Please Help Me .
Thaks

VivekG
Автор

The first approach is working but the second approach is not working. Any suggestions please...


alert(data.Name);
$('#txtname').val(data.Name); The alert statement displays Undefined message

sushanthsreedharan
Автор

Why do we removed contenttype from the $.ajax() script ??

gopikrishnan
Автор

I'm getting [object][object] in alertbox when I apply it on actual online server. is there a solution to this problem?

alimuc
Автор

Hi can any body suggest to retrieve huge dataset say 1 million records available on the table by serialisation approach.. suggest the Best way to do that..

shahidvayam
Автор

but its not working on live server its working on localhost

devendrakushwaha
Автор

how to read json data from mobile to wcf

sadiqsadiq