MVC viewmodel构造函数

use*_*365 3 asp.net-mvc

在viewmodel的构造函数中填充viewmodel的模型/变量是一种好习惯吗?

例如:

public class ProgramViewModel
{
    public IEnumerable<Programme> ProgramList { get; set; }
    public string QuerystringAgeID { get; set; }

    public ProgramViewModel()
    {
        QuerystringAgeID = HttpContext.Current.Request.QueryString["QuerystringAgeID"];
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 6

在viewmodel的构造函数中填充viewmodel的模型/变量是一种好习惯吗?

这取决于.

但是通过你所展示的例子,答案是否定的.你有一个模型绑定器应该这样做:

public class ProgramViewModel
{
    public IEnumerable<Programme> ProgramList { get; set; }
    public string QuerystringAgeID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后:

public ActionResult Foo(ProgramViewModel model)
{
    // model.QuerystringAgeID will be automatically populated 
    // with the value of the QuerystringAgeID 
    // thanks to the default model binder
    ...
}
Run Code Online (Sandbox Code Playgroud)

除此之外,您绝对应该避免HttpContext.Current在ASP.NET MVC应用程序中使用.使您的代码绑定到ASP.NET上下文,使得无法单独重用和单元测试.ASP.NET MVC为您提供了这样的抽象:HttpContextBase,...