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

后端 未结 2 938
不知归路
不知归路 2020-12-29 16:19

I have a custom modelbinder, its check the authentication cookie and return the value.

public class UserDataModelBinder : IModelBinder
{
    public          


        
相关标签:
2条回答
  • 2020-12-29 17:16

    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.

    0 讨论(0)
  • 2020-12-29 17:17

    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.

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