Jul 27, 2015

ASP.NET MVC: Access an action only by ajax

It’s very simple actually. ASP.NET MVC provides a bunch of extension points, and this is one of them. There’s an class in the framework called ‘ActionMethodSelectorAttribute’,

which contains only one method, which returns true if the call is permitted, false if it isn’t. On each call to an action, the framework checks for any attributes on the method which implement this class, and makes sure all of these return true. Simply put: we’ll implement the class in such a way that it will return true when the action is called via ajax:

public class AjaxRequestAttribute : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.Request.IsAjaxRequest();
    }
}


I told you it was simple. Now you can use this attribute in your controllers, as such:




public class HomeController : Controller
{
    [AjaxRequest]
    public ActionResult Index()
    {
        return View();
    }
}


When you go to /Home via your web browser now, you will get a 404, page does not exist. However, when you call /Home via ajax, you’ll get the HTML output from the view returned. That’s it.


No comments:

Post a Comment