Search This Blog

Tuesday, October 4, 2016

Parsing JSON result using dynamic Expressions in MVC

Talking of MVC application, there could be many instances where we return simple JSON objects to the View with 2-3 properties. In such cases we might not want to create classes and returning the same to view as modal. In such scenarios we can easily use "dynamics" to parse the JSON object. Have a look at the example below:

We need to return more than one value in JSON, so instead of creating a class we created an object and returned it as JSON.

public JsonResult GetData()
          var customObject = new
              ID = 1,
              Name = "Demo",
              Company = "TechPerspect"
          return Json(customObjectJsonRequestBehavior.AllowGet);

Now we can call this method in our HttpGet request of our Modal and retrieve the properties using dynamic object as shown below:

        public async ActionResult Manage()
            dynamic returnedObject = base.GetData().Data;
            ViewBag.ID = returnedObject.ID;
            ViewBag.Name = returnedObject.Name;
            ViewBag.Company = returnedObject.Company;
            return View();

No comments:

Post a Comment