Passing JSON data from controller to the view
UserDetailController.cs
[HttpPost]
[ValidateInput(false)]
public JsonResult FetchUserDetailsByid(string userID)
{
List<UserDetailByID>ย userDetailollection;
try
{
//return the User Details List
userDetailollection = new GetUserDetailsByidModel().FetchUserDetailByid(UserID));
}
catch (Exception ex)
{throw ex;
}
var jsonSerializer = new JavaScriptSerializer();
string output = jsonSerializer.Serialize(userDetailollection );
return Json(new
{
output
}, JsonRequestBehavior.AllowGet);
}
Includedย Namespace:
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Script.Serialization;
View (JQUERY)
$.ajax({url: “@Url.Action(“FetchUserDetailsByid”, “UserDetail”)”,
data: “{ ‘userID’: ‘” + userID + “‘ }”,
dataType: “json”,
type: “POST”,
contentType: “application/json; charset=utf-8”,
success: function(data)
{
//Converting JSON String to JSON Object
var jsonObject = $.parseJSON(data.output);
if (parseInt(jsonObject.length) > 0)
{
alert( jsonObject[0].UserName);
}
},
error: function(result) {
alert(“Error”);
}
Note :
1.ย URLย “FetchUserDetailsByid” be the name of the method
ย ย ย ย ย ย ย ย ย ย ย ย “UserDetail” be the name of the controller
2. “var jsonObject = $.parseJSON(data.output);” is used to converting
ย ย ย ย ย ย ย ย json string to object
This site is absolutely fabulous!