Wednesday, August 5, 2009

ASP.NET MVC Extensibility -Part1

In this post i am going to show you how to extended MVC Framework ActionResult & ActerFilterAttribute 

ActionResult

In ASP.NET MVC  Framework user request are  routed to the Controller then controller will invoke right action and returns the ActionResult as view.  The view can be one of the following

  1. ContentResult – Simply writes the returned data to the response.
  2. EmptyResult – Returns an empty response.
  3. HttpUnauthorizedResult – Returns Http 401 code for non authorized access.
  4. JsonResult – Serializes the response to Json.
  5. RedirectResult – Redirects to another Url.
  6. RedirectToRouteResult – Redirects to another controller action.

Now we are going to extend the ActionResult to return the XML document .

Let we have Model  which describes Contacts Details with the following attribute  Name,Email, Phone, MSNMessengerID, WebPage etc.. now we wanted to return this Model as XML document as ActionResult.

My Model Class Definition:

image 


Next we need to create XML  ActionResult  class which is derived from ActionResult class.



Here is the ActionResult class.



using System;
namespace System.Web.Mvc {
// Summary:
// Encapsulates the result of an action method and is used to perform a framework-level
// operation on the action method's behalf.
public abstract class ActionResult {
protected ActionResult();

// Summary:
// Enables processing of the result of an action method by a custom type that
// inherits from System.Web.Mvc.ActionResult.
//
// Parameters:
// context:
// The context within which the result is executed.
public abstract void ExecuteResult(ControllerContext context);
}
}


XMLDocumentResult Derived from ActionResult


we need to override ExecuteResult method.  here  i am serializing the object as XML and retuning it.  


using System.Web;
using System.Web.Mvc;
using System.Xml.Serialization;
namespace MVCExten.code
{
public class XmlDocumentResult :ActionResult
{
private object xmlSerializeable;
public XmlDocumentResult() {
}
public XmlDocumentResult(object xmlSer)
{
this.xmlSerializeable = xmlSer;
}
public object XmlSer
{
get { return xmlSerializeable; }
}
public override void ExecuteResult(ControllerContext context)
{
if (xmlSerializeable !=null)
{
XmlSerializer xml = new XmlSerializer(xmlSerializeable.GetType());
// context.HttpContext.Response.ContentType ="text/xml";
xml.Serialize(context.HttpContext.Response.Output, xmlSerializeable);
}
}
}
}


Now let us create new action in home controller which returns the XmlDocumentResult



image



Here is the ActionResult render to the client



image



So  now we can able to create custom ActionResult for anything fox example  RSS feed document.



Next Post we will see about ActionFilterAttribute and how to use it.



Thanks(Nandri)



SreenivasaRagavan.

No comments: