MVC视图模型构造函数
问题描述:
是否在viewmodel的构造函数中填充视图模型的模型/变量是一种好的做法?MVC视图模型构造函数
例如:
public class ProgramViewModel
{
public IEnumerable<Programme> ProgramList { get; set; }
public string QuerystringAgeID { get; set; }
public ProgramViewModel()
{
QuerystringAgeID = HttpContext.Current.Request.QueryString["QuerystringAgeID"];
}
}
答
是它填充视图模型的模型/变量 视图模型的构造好的做法呢?
这取决于。
但是用您所示的例子,答案是no。您有应该做一个模型绑定:
public class ProgramViewModel
{
public IEnumerable<Programme> ProgramList { get; set; }
public string QuerystringAgeID { get; set; }
}
然后:
public ActionResult Foo(ProgramViewModel model)
{
// model.QuerystringAgeID will be automatically populated
// with the value of the QuerystringAgeID
// thanks to the default model binder
...
}
此外,你应该绝对避免在ASP.NET MVC应用程序中使用HttpContext.Current
。使您的代码绑定到ASP.NET上下文,从而无法单独重用和单元测试。 ASP.NET MVC为您提供这样的抽象:HttpContextBase,...