I want to use partial views with AJAX calls in ASP.NET MVC, and this is the first time I\'m using it. I just searched to see if there is anything special I should know befor
For those looking for a .NET Core solution it's a little bit more involved, as IsAjaxRequest() is no longer available.
Below is the code I've used in production on several projects to great effect.
public class AjaxOnlyAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor actionDescriptor)
{
if(routeContext.HttpContext.Request.Headers != null &&
routeContext.HttpContext.Request.Headers.ContainsKey("X-Requested-With") &&
routeContext.HttpContext.Request.Headers.TryGetValue("X-Requested-With", out StringValues requestedWithHeader))
{
if(requestedWithHeader.Contains("XMLHttpRequest"))
{
return true;
}
}
return false;
}
}