Child Actions - Restrict to Ajax Request Only

21 Apr 2015

1 . Create an attribute filter AjaxChildActionOnlyAttribute and override IsValidForRequest() method.

namespace Website.AttributeFilters
{
    public class AjaxChildActionOnlyAttribute : ActionMethodSelectorAttribute
    {
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest() || controllerContext.IsChildAction;
        }
    }
}

2 . Add the newly created custom attribute to the child action.

[AttributeFilters.AjaxChildActionOnly]
public PartialViewResult AsyncWidget()
{
    return PartialView("_AsyncWidget");
}