Showing posts with label MVC ActionMethodSelectorAttribute Controllers. Show all posts
Showing posts with label MVC ActionMethodSelectorAttribute Controllers. Show all posts

Thursday, 29 December 2011

Using ActionMethodSelectorAttribute in MVC

If you want an MVC controller action to be only available for Ajax methods, use theAjaxMethodSelectorAttribute. Inherit this abstract class to create the attribute AjaxOnlyAttribute below and tag this attribute with your method:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TestActionMethodSelectorAttribute.Attributes
{
public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
}
}


Usage (testing the attribute out in HomeController):



[AjaxOnly]
public ActionResult About()
{
return View();
}


If the current request is not an AjaxRequest, a Http 404 is returned. The attribute [HttpPost] and [HttpGet]is inherited from the ActionMethodSelectorAttribute. They also implement the abstract method IsValidForRequest.