[RESOLVED]Rendering JSON Result on Razor View

Hi All_

i have a controller action method as below

public JsonResult WidgetDisplay()

{
List<Users> ul = new List<Users>();
using (var x = new AlfaTestEntities())
{
var result = from p in x.tblUsers
select p;
Users l = null;
try
{
foreach (var c in result.ToList())
{
l = new Users();
l.UserId = c.UserId;
l.WidgetA = (bool)c.WidgetA;
l.WidgetB = (bool)c.WidgetB;
l.WidgetC = (bool)c.WidgetC;
ul.Add(l);
}
}
catch (Exception ex)
{
}
}
return Json(ul, JsonRequestBehavior.AllowGet);
}

where i’m returning a json result to the view , can some one post the code on how to display the json data on the view.

I believe, when you return the JsonResult, you are not using the View in fact – so you may see a browser dialogue box or so to download the json data.

Typical example of the correct usage of it, is – to call this action method from some other view – with xmlHttpRequests or by using jQuery ($.getJson or $.ajax etc). These helper methods can handle the success event by passing the result object (which was
sent from action method) as a parameter for the success events.

You can later use this result (or data) parameter same as a normal javascript object with full properties, etc to iterate the items and to display the items.

Following article helps to demonstrate this:
http://chsakell.com/2013/06/08/retrieve-json-data-from-mvc-controllers-in-asp-net-mvc/
Another discussion which has example:

http://stackoverflow.com/questions/18831512/calling-json-from-mvc-view

On the other note, if you want to use dedicated View, then it is probably good for you to use ViewResult.

See this discussion:

http://stackoverflow.com/questions/15196528/how-to-return-json-object-from-mvc-controller-to-view

Leave a Reply