0

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.

0

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply. However, this still will have 2 round trips to server which I want to avoid. I want to return just the Json data via my List action and display it via template plugin. Any help?
1

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 e.g

  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>

6 Comments

I am trying the same above code with Razor syntax which is failing. I am trying as: var json = @Model.ToJson();
well 'failing' is not much use to me - have you got more info? Has the Model got a ToJson method?
No. I have a separate static class for ToJson as mentioned by you above. However as soon as the compiler hits @Model.ToJson(), it throws error "'System.Collections.Generic.List<MyNameSpace.Models.MyClass>' does not contain a definition for 'ToJson'"
Well the extension method is added to the html helper not to the model object. Notice the Html.ToJson rather than Model.ToJson
I tried your method too with the following syntax: @Html.ToJson((List<MyNamespace.Models.MyClass>)Model); which gives me javascript error "Message: Expected identifier, string or number Line: 64 Char: 18 Code: 0 URI: localhost/MyWebApplication"
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.