Saturday, March 24, 2012

Creating Custom MVC ActionResults

One of the most powerful things in MVC is how easy it is to extend, a really good example is ActionResults.  Basically all you have to do is inherit the ActionResult class and override the ExecuteResult method and add a constructor, with a few lines for code you can have an action return anything you want from dynamically generated pdf and xls files, to images. 

Here is an example of returning an object as xml
   1: public class XmlResult : ActionResult
   2: {
   3:     private readonly object _item;
   5:     public XmlResult(object item)
   6:     {
   7:         _item = item;
   8:     }
  10:     public override void ExecuteResult(ControllerContext context)
  11:     {
  12:         if (_item != null)
  13:         {
  14:             var xs = new XmlSerializer(_item.GetType());
  15:             context.HttpContext.Response.ContentType = "text/xml";
  16:             xs.Serialize(context.HttpContext.Response.Output, _item);
  17:         }
  18:     }
  19: }

basically you pass the object you want serialized into the constructor, and return it.  Inside the ExecuteResult method I do a quick null check, spin up a XmlSerializer set the response content type to “text/xml” and use the HttpContext.Response.Output to write the serialized data.

All you have to do to use it is create a new instance and return it from your action
   1: public ActionResult Index()
   2: {
   3:     var model = new BasicDemoModel();
   4:     return new XmlResult(model);
   5: }

To see the code used checkout the sample application at here.

No comments: