简体   繁体   中英

ASP.Net MVC List action returning Json Data

I have a scenario where-in I am trying to use the jQuery template plugin for displaying list of data on my MVC list view. However my list is the default view of my mvc application. I want to use the same action to server both purposes of returning json data as well as returning view.

It is making double trip for getting data. Is there a way that as soon as my action is called, I return Json data and use the template plugin to display data.

You can test if the action has been called with AJAX then return JSON data and if not return a normal view:

public ActionResult Index()
{
    var model = FetchModel();
    if (Request.IsAjaxRequest())
    {
        return Json(model, JsonRequestBehavior.AllowGet);
    }
    return View(model);
}

Of course this if makes your controller action ugly. It would be far better to use action filters to avoid repeating this logic in multiple actions:

public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            var viewResult = filterContext.Result as ViewResultBase;
            if (viewResult != null)
            {
                if (viewResult.Model != null)
                {
                    filterContext.Result = new JsonResult
                    {
                        Data = viewResult.Model,
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
            }
        }
    }
}

And then decorate your controller with this attribute:

[MyFilter]
public ActionResult Index()
{
    var model = FetchModel();
    return View(model);
}

Your comment to Darins great answer leads me to believe you need the following which your question does not really explain.

If I have not crossed my wires then this my help...

You can return a html view but also include a script tag that includes a json object.

Create a toJson html helper extension eg

  public static class MvcViewExtensions 
  {

    public static string toJson(this System.Web.Mvc.HtmlHelper helper, object obj)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        return serializer.Serialize(obj);
    }
  }

Then in you view something like this

<html>

    ...other html stuff

    <script>

        var json = <%= Html.ToJson(Model.someProperty) %>;
        //call to some js to do your templating
        myapp.someTemplatingFunc(json);

    </script>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM