Return Json object from Asp.net webMethod to Ajax call
Include using Newtonsoft.Json;
CS
public string CheckDetails(string param1, string param2){ var chk = new check { subject = "hello! " +param1 , description = param2 +" Years Old" }; return JsonConvert.SerializeObject(chk);}public class check{ public string subject { get; set; } public string description { get; set; }}
HTML
<div> <input type="text" name="name" id="txtname"/> <input type="text" name="age" id="txtage"/> <input type="button" id="btnSubmit" value="details"/></div>
Jquery
$(function () { $('#btnSubmit').on('click', function () { var options = { type: "POST", url: '/Ajax/CheckDetails/', data: '{param1:"' + $('#txtname').val() + '",param2:"' + $('#txtage').val() + '"}', async: false, cache: false, dataType: "json", contentType: "application/json; charset=utf-8", success: function (response) { if (response != null && response.d != null) { var data = response.d; alert(typeof (data)); //it comes out to be string //we need to parse it to JSON data = $.parseJSON(data); alert(data.subject); alert(data.description); } } }; $.ajax(options); }); });
To return a JSON object you need to serialize your response. In your method return something like return JsonConvert.SerializeObject(new { subject = subject, description = Description });
You will need to add a using
statement at the top for using Newtonsoft.Json;
.
In order to avoid errors about using unassigned variables, you will need to give your subject
and Description
variables starting values like `string subject = "". That way if they do not get a new value, they return empty strings.
Instead of creating a generic object of new { subject = subject, description = Description }
, you could indeed create a class containing those properties:
public class EmailTemplate{ public string Subject { get; set; } public string Description { get; set; }}
And then serialize it the same way above: JsonConvert.SerializeObject(new EmailTemplate{ subject = subject, description = Description });
But if you aren't going to use that model class anywhere else, it isn't necessary.
Finally, in your JavaScript, you should be able to access the data like this:
success: function (data) { console.log("Subject:" + data.subject); console.log("Description:" + data.description);}
You may return Json(Your_object)
function. But you have to change your method signature to return IHttpActionResult
.An use model to return values.For example:
public class EmailModel{ public string TemplateSubject {get;set;}public string TemplateDescription {get;set;}}
Then your return instruction will look like
return Json(emailModel);