2012-02-21 12 views
3

viewmodelのコンストラクタでビューモデルのモデル/変数を設定することをお勧めしますか?例えばMVC viewmodelコンストラクタ

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

    public ProgramViewModel() 
    { 
     QuerystringAgeID = HttpContext.Current.Request.QueryString["QuerystringAgeID"]; 
    } 
} 

答えて

6

でのviewmodelのコンストラクタをのviewmodelのモデル/変数を移入することをお勧めしますか?

によって異なります。

あなたが示した例では、回答はで、です。

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、

関連する問題