Razor MVC, where to put global variables that's accessible across master page, partiview and view?

前端 未结 1 1097
醉话见心
醉话见心 2020-12-13 20:42

Hello Razor MVC Gurus:

Newbie question.

Background. I have a custom IIdentity that is set in an HttpModule before it gets to controller &a

相关标签:
1条回答
  • 2020-12-13 21:15

    I'll explain a similar solution that works pretty well for me. With small changes, I believe that it will work for you (and others, hopefully) as well.

    Basically, we'll be using inheritance.

    Controllers

    Let's create a custom base controller, such as

    public class BaseController : Controller
    

    and let's change our controllers to inherit from it, as

    public class HomeController : BaseController
    

    Models (ViewModels, I say)

    You probably have lots of classes inside your Models folder, right? They act as DTOs from the controller to the views, right²? If you answered yes for both, then keep reading.

    Let's create a base model class, such as public class BaseVM, and let's change our models to inherit from it, like public class HomeIndex : BaseVM

    Important: your layout file (_Layout or whatsoever) must be strongly typed to BaseVM or a child of it.

    The hook

    Now that everything's beautifuly typed, let's use the request pipeline in our favor. At BaseController, you'll add a method that looks like this:

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResultBase)//Gets ViewResult and PartialViewResult
        {
            object viewModel = ((ViewResultBase)filterContext.Result).Model;
    
            if (viewModel != null && viewModel is BaseVM)
            {
                BaseVM baseVM = viewModel as BaseVM;
    
                baseVM.MyIdentity = (MyIdentity)((GenericPrincipal)context.User).Identity;
                //and so on...
            }
        }
    
        base.OnActionExecuted(filterContext);//this is important!
    }
    

    OnActionExecuted is called after the execution of the action but before the view rendering. That's exactly what we want.

    I hope you got it already. =)

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