Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to populate a base viewmodel

I know there are two ways to populate a base modelview:

First way, using OnActionExecuted method:

public abstract class BaseController : Controller
{
    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);

        var result = filterContext.Result as ViewResultBase;
        if (result != null)
        {
            var model = filterContext.Controller.ViewData.Model as BaseViewModel;

            if (model != null)
            {
                model.CurrentUser = HttpContext.Current.Request.Cookies["CurrentUser"].Value;
            }
        }
    }

Second way, property get accessor:

public abstract class BaseViewModel
{
    public string CurrentUser
    {
        get
        {
            return HttpContext.Current.Request.Cookies["CurrentUser"].Value;
        }
    }
}

Which way is better? any pros/cons I'm missing?

like image 222
Myself Avatar asked Dec 05 '11 16:12

Myself


1 Answers

I'd do it the second way, as it'd be a little more clearer as to what the model value of CurrentUser is, without having to go poking around in the controllers.

like image 157
Brandon Avatar answered Oct 06 '22 20:10

Brandon