Your partner in IT success

A specialized company in providing high quality consultancy on analysis, architecture and development projects

 
31
Jan
.NET / Ajax / ASP.NET / C# / MVC

How to limit a call to a MVC action in AJAX mode only?

With the ASP.NET MVC framework, it is possible to use attributes to filter calls to action and ensure that they run only in certain cases. For example, the attribute HttpPost ensures that action will be executed only when an HTTP Post is issued.

Like this attribute, there may be cases where it is desired that the action is executed only in the context of an AJAX call. It would be a shame not to take advantage of the extensibility of the framework, so we'll create our own filter attribute. There is an extension method IsAjaxRequest on the Request object that we can use.

using System;
using System.Reflection;
using System.Web.Mvc;
 
namespace DevOne.Framework.Web.Mvc
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class AjaxAttribute : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
        {
            #region Validation
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            #endregion
 
            return controllerContext.HttpContext.Request.IsAjaxRequest();
        }
    }
}

Now, just to decorate the actions for which you want to restrict the AJAX call.

public class BlogController : Controller
    {
        //
        // POST: /Blog/Comment
 
        [HttpPost, Ajax]
        public ActionResult Comment(BlogComment comment)
        {
            
        }
    }

Simple and effective, right?

Posted by Fabian Vilers, Consulting Principal

Add your comment