Extending ViewResult in asp.net MVC 2

Posted on April 21, 2011

0


I recently needed to return JSON and HTML from the same controller method. One way to handle this is to extend ViewResult and create a new Custome result. Here is a good and nearly complete example. There are a couple of extra steps you need to take to get this example working, as follows.

1.) Extend Controller to enable new ViewResult creation.
This may not be the most efficient way to do this, I’m going to look at custom view engines as an alternative but here is the gist of what works for me currently. Create a base controller:

public class DixonController : Controller
    {
        public ViewResult HtmlOrJsonView(object model)
        {
            ViewData.Model = model;
            return new HtmlOrJsonView(){ViewData = ViewData};
        }
    }

This controller has a method HtmlOrJsonView which creates a new custom view. One thing to point out at this point is; remember to pass in ViewData. I  a spent a good while trying to figure out why my models were not showing up in the View.

With our new ViewResult we have one important method we must override.


    public class HtmlOrJsonView : ViewResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            if (context.HttpContext.Request.IsAjaxRequest())
            {

                ExecuteJsonView(context);
            }
            else
            {
                ExecuteHtmlView(context);
            }
        }
    }

This method is called by the MVC framework after it has been returned from our controller method. You can see in this example we either return JSON or HTML. I wont go into details about these methods but you get the general idea.

We can now create our own Contollers that extend DixonController and can return our new ViewResult.

    public class TestController : DixonController
    {
        public virtual ActionResult ReturnHtmlOrJson()
        {
            //...Get  model here ...
            return HtmlOrJsonView(model);
        }
    }

Thats it!

Advertisements
Posted in: asp.net MVC