Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC viewmodel constructors

Tags:

asp.net-mvc

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"];
    }
}
like image 785
user441365 Avatar asked Dec 04 '25 02:12

user441365


1 Answers

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, ...

like image 72
Darin Dimitrov Avatar answered Dec 05 '25 18:12

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!