当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc - MVC viewmodel constructors

问题描述:

Is it good practice to populate the models/variables of a viewmodel in the constructor of the viewmodel?

For instance:

public class ProgramViewModel

{

public IEnumerable<Programme> ProgramList { get; set; }

public string QuerystringAgeID { get; set; }

public ProgramViewModel()

{

QuerystringAgeID = HttpContext.Current.Request.QueryString["QuerystringAgeID"];

}

}

网友答案:

Is it good practice to populate the models/variables of a viewmodel in the constructor of the viewmodel?

It depends.

But with the example you have shown, the answer is no. You have a model binder that is supposed to do that:

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

and then:

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

In addition to that you should absolutely avoid using HttpContext.Current in an ASP.NET MVC application. Makes your code tied to an ASP.NET context making it impossible to reuse and unit test in isolation. ASP.NET MVC provides you abstractions for this: HttpContextBase, ...

分享给朋友:
您可能感兴趣的文章:
随机阅读: