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
- ContentResult – Simply writes the returned data to the response.
- EmptyResult – Returns an empty response.
- HttpUnauthorizedResult – Returns Http 401 code for non authorized access.
- JsonResult – Serializes the response to Json.
- RedirectResult – Redirects to another Url.
- 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:
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
Here is the ActionResult render to the client
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:
Post a Comment