To solve JSON Date formatting issue and cameCase formatting issue, click here.
To return JSON (JavaScript Object Notation) content from controller, we use JsonResult
return type in the action method of the controller.
CONTROLLER CODE
public JsonResult OutputToJson() { UserNamePasswordModel model = new UserNamePasswordModel() { Password = "India", UserName = "Tamjid" }; return Json(model, JsonRequestBehavior.AllowGet); }
In the above code, we are setting the properties of the UserNamePasswordModel
object and converting into JSON by Json
method and returning to the view. Depending on which browser used, it may download the Json string or write it as output in the browser window. If called from the AJAX, it returns to the calling JavaScript function.
OUTPUT
{"UserName":"Tamjid","Password":"India","Active":false}
There are different ways, we can convert the model object to JSON string and return to the browser.
return Json(model, JsonRequestBehavior.AllowGet);
System.Web.Script.Serialization.JavaScriptSerializer serializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
return Json(serializer.Serialize(model), JsonRequestBehavior.AllowGet);
// OUTPUT
// "{\"UserName\":\"Tamjid\",\"Password\":\"India\",\"Active\":false}"
return Json(Newtonsoft.Json.JsonConvert.SerializeObject(model), JsonRequestBehavior.AllowGet);
// OUTPUT
// "{\"UserName\":\"Tamjid\",\"Password\":\"India\",\"Active\":false}"
"{\"UserName\":\"Tamjid\",\"Password\":\"India\",\"Active\":false}"Views: 45427 | Post Order: 64