ASP.NET MVC > Output

JSON result in ASP.NET MVC

How to return JSON result from ASP.NET MVC controller action method?

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.


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.



Different ways to convert the model to JSON string and return

There are different ways, we can convert the model object to JSON string and return to the browser.

The default way

return Json(model, JsonRequestBehavior.AllowGet);

Using JavaScriptSerializer to convert model to JSON string

System.Web.Script.Serialization.JavaScriptSerializer serializer = 
new System.Web.Script.Serialization.JavaScriptSerializer();

return Json(serializer.Serialize(model), JsonRequestBehavior.AllowGet);

// "{\"UserName\":\"Tamjid\",\"Password\":\"India\",\"Active\":false}"

Using NewtonSoft to convert model to JSON string

return Json(Newtonsoft.Json.JsonConvert.SerializeObject(model), JsonRequestBehavior.AllowGet);

// "{\"UserName\":\"Tamjid\",\"Password\":\"India\",\"Active\":false}"

 Views: 3954 | Post Order: 64

Write for us