Is there any attribute relating to AJAX to be set for ASP.NET MVC controller actions?

后端 未结 6 894
轻奢々
轻奢々 2020-11-30 02:13

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

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 03:02

    ASP.NET MVC provides an extension method to check if an Request is an Ajax Request. You can use it to decide if you want to return a partial view or json result instead of a normal view.

    if (Request.IsAjaxRequest())
    {
        return PartialView("name");
    }
    return View();
    

    To limit an action method to Ajax calls only you can write a custom attribute. In case of a normal request this filter will return a 404 not found http exception.

    [AttributeUsage(AttributeTargets.Method)]
    public class AjaxOnlyAttribute : ActionFilterAttribute
    {
         public override void OnActionExecuting(ActionExecutingContext filterContext)
         {
            if (!filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.HttpContext.Response.StatusCode = 404;
                filterContext.Result = new HttpNotFoundResult();
            }
            else
            {
                base.OnActionExecuting(filterContext);
            }
         }
    }
    

    you can use it like that:

    [AjaxOnly]
    public ActionResult Index() {
        // do something awesome
    }
    

提交回复
热议问题