我知道有两种方法可以填充基础模型视图:
首先,使用OnActionExecuted方法:
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;
}
}
}
第二种方式,属性获取访问者:
public abstract class BaseViewModel
{
public string CurrentUser
{
get
{
return HttpContext.Current.Request.Cookies["CurrentUser"].Value;
}
}
}
哪种方式更好?我缺少任何利弊?
答案 0 :(得分:2)
我会以第二种方式进行,因为CurrentUser
的模型值更加清晰,而不必在控制器中进行探索。