How do I pass value to MVC3 master page ( _layout)?

大憨熊 提交于 2019-11-30 05:28:50

We did it as follows:

  1. Defined separate viewmodel for masterpages.

    public class MasterPageViewModel
    {
        public Guid CurrentUserId { get; set; }
        public string CurrentUserFullName { get; set; }
    }
    
  2. Added injection filter and filter provider.

    public class MasterPageViewModelInjectorFilterProvider: IFilterProvider
    {
        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            return new [] {new Filter(new MasterPageViewModelInjectorFilter(), FilterScope.Action, null), };
        }
    
        private class MasterPageViewModelInjectorFilter: IResultFilter
        {
            public void OnResultExecuting(ResultExecutingContext filterContext)
            {
                var viewResult = filterContext.Result as ViewResult;
                if (viewResult == null)
                    return;
    
                if (viewResult.ViewBag.MasterPageViewModel != null)
                    return;
    
                //setup model whichever way you want
                var viewModel = new MasterPageViewModel();
                //inject model into ViewBag
                viewResult.ViewBag.MasterPageViewModel = viewModel;
            }
    
            public void OnResultExecuted(ResultExecutedContext filterContext)
            {
            }
        }
    }
    
  3. Configure filter provider:

    //in Application_Start
    FilterProviders.Providers.Add(new MasterPageViewModelInjectorFilterProvider());
    
  4. Use in master:

    ViewBag.MasterPageViewModel
    

This way you have fine uncoupled architecture. Of course you can combine it with Dependency Injection (we do, but I left it out for clarity) and configure your action filter for every action whichever way you want.

In this case you can use ViewBag.

public ActionResult Index(UserData userData)
{
    AccountLoginWidgetVM model = new AccountLoginWidgetVM();
    if (null != userData)
        model.UserData = userData;

    ViewBag.UserData = userData;
    return View(userData);
}


@Html.RenderPartial("LoginPartial", ViewBag.UserData)

You have to make sure that userData is not null. If it'll be null the passed model will be default model of the view.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!