Reputation: 397
I have just a quick question about how to properly pass data to a view using the MVC pattern.
I have an EditProfile/Register model (Name, Email, Country). The View has a country dropdown list, and I need to pass it a list of countries.
Is it to correct to create a new model (just for the view), that basically encapsulates my EditProfile/Register model, and a List? Do I create this view specific model in the controller? (as opposed to my data access project).
Thanks!
Upvotes: 1
Views: 294
Reputation: 1842
you have two ways to accomplish this task
(i) Recommended
create a viewmodel add a property of type selectlist
<code>
public SelectList countrylist
{
get;
set;
}
</code>
in the constructor function of your viewmodel class assign list of countries from country table.
<code>
countrylist= new SelectList(db.countries.ToList(), "CountryID", "CountryName");
</code>
in the view you add
<code>
Html.DropDownList("CountyID", Model.countrylist,"Select")
</code>
(ii)use only if you have to use this model with very few views(as seems in your case)
do not make a viewmodel, use jquery instead, and in the document ready of vew page add a html select for country list.
Upvotes: 0
Reputation: 100620
View models (for ASP.Net MVC views) are not related to domain models (one in data layer) except the name. This MVC: Data Models and View Models question covers the differences/similarities in details.
You create view model somewhere in your ASP.Net MVC project (not in data layer) and usually put in "Models" or "ViewModels" folder sibling to Controllers folder. Depending on views some view model classes can be shared, but you'll also have some that used by single view.
Upvotes: 2