ASP.NET MVC - Set ViewData for masterpage in base controller

后端 未结 1 1983
悲&欢浪女
悲&欢浪女 2020-12-07 09:05

I\'m using a masterpage in my ASP.NET MVC project. This masterpage expects some ViewData to be present, which displays this on every page.

If I don\'t set this ViewD

相关标签:
1条回答
  • 2020-12-07 09:39

    I see two options:

    First:

    Set the ViewData for MasterPage in YourBaseController.OnActionExecuting() or YourBaseController.OnActionExecuted():

    public class YourBaseController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Optional: Work only for GET request
            if (filterContext.RequestContext.HttpContext.Request.RequestType != "GET")
                return;
    
            // Optional: Do not work with AjaxRequests
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                return;
    
            ...
    
            filterContext.Controller.ViewData["foo"] = ...
        }
    }
    

    Second:

    Or create custom filter:

    public class DataForMasterPageAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Optional: Work only for GET request
            if (filterContext.RequestContext.HttpContext.Request.RequestType != "GET")
                return;
    
            // Optional: Do not work with AjaxRequests
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                return;
    
            ...
    
            filterContext.Controller.ViewData["foo"] = ...
        }
    }
    

    and then apply to your controllers:

    [DataForMasterPage]
    public class YourController : YourBaseController
    {
        ...
    }
    

    I think the second solution is exactly for your case.

    0 讨论(0)
提交回复
热议问题