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

后端 未结 6 892
轻奢々
轻奢々 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 02:54

    A spinoff of Muhammad's answer letting you specify that it mustn't be an ajax request as well:

    using System.Web.Mvc;
    public class AjaxAttribute : ActionMethodSelectorAttribute
    {
        public bool ajax { get; set; }
        public AjaxAttribute() { ajax = true; }
        public AjaxAttribute(bool a) { ajax = a; }
        public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
        {
            return ajax == controllerContext.HttpContext.Request.IsAjaxRequest();
        }
    }
    

    This lets you do things like...

    [Ajax]
    public PartialViewResult AjaxUpdatingPage() {
        return PartialView();
    }
    
    [Ajax(false)]
    public ViewResult NotAjaxUpdatingPage() {
        return View();
    }
    

提交回复
热议问题