JSON result in ASP.NET MVC

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


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}

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);

// OUTPUT
// "{\"UserName\":\"Tamjid\",\"Password\":\"India\",\"Active\":false}"
Using NewtonSoft to convert model to JSON string
return Json(Newtonsoft.Json.JsonConvert.SerializeObject(model), JsonRequestBehavior.AllowGet);

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

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...