Friday 8 January 2010

MVC: Creating custom attributes using "ActionMethodSelectorAttribute".

Hi,

Welcome back!

In MVC application you have encounter many MVC attributes like HandleError and many more. These attributes servers one particular task so that you do not have to re-write the code for for it.

If you want to write your attribute in controller, then how can we do that?
MVC provides one class named ActionMethodSelectorAttribute, which can help us to create our own custom attribute. Let's create our own attrubite "AjaxMethodAttribute". This attribute tests the Ajax request. If the request from Ajax method came, allow the action to execute. The request other than the Ajax should be neglected.


We will create the class named AjaxMethodAttribute inherited from ActionMethodSelectorAttribute.
The class ActionMethodSelectorAttribute has one override method IsValidForRequest which has to be implemented.
Here is our implementation.

public class AjaxMethodAttribute : ActionMethodSelectorAttribute
    {
        ///
        /// Implement IsValidForRequest method as per your need.
        ///
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
// Check request of Ajax.
            return controllerContext.HttpContext.Request.IsAjaxRequest();
        }
    }

You can now have our custom attribute ready for use. Let's try it.

[AjaxMethodAttribute] public ActionResult AjaxRequest() { ViewData["AjaxCall"] = "Call from Aajx Request"; return View("AjaxRequest"); }

Hope you enjoy this blog. Keep watching for more blogs...

No comments:

Post a Comment