简体   繁体   中英

My Masterpage uses a viewmodel that all my other models inherit from, how to simplify this?

I use the model:

public void MasterViewModel
{
   public CurrentSession Session {get;set;}
}

And then all my other view models look like:

public void LoginViewModel : MasterViewModel
{

}

The problem is, I have to initialize my MasterViewModel in each and every action like this:

public ActionResult Index()
{
  var model = new WelcomeIndexViewModel
  {
     Session = this.GetSession(); // from my base controller
  }

  ..
}

My basecontroller has the method GetSession()

Is it possible to set this value in my basecontroller somehow so I don't have to do this in each action method?

One thing you could do, in your BaseController override OnResultExecuting , hijack the view model and inject the Session variable int, like this:

public class BaseController : Controller
{
    protected override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var viewResult = filterContext.Result as ViewResult;
        if (viewResult != null)
        {
            var viewModel = viewResult.Model as MasterViewModel;
            if (viewModel != null)
            {
                viewModel.Session = GetSession();
            }
        }
        base.OnResultExecuting(filterContext);
    }
}

Note: This is only checking if you use return View(model); in your controller, you might also check for other action results too (like partial views, json etc...)

Hope this helps.

You can create a decorator function for the Controller.View function, that would initialize the session for you.

Something like -

internal ActionResult ExtendedView(object model)
    {
        Session = this.GetSession();

        return View(model);
    }

Then, instead of using the return View(model), use return ExtendedView(model).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM