Maybe this is very simple to do but I can’t find the good words when I search on stackoverflow or on google.
I have a model and this model contains a “Country” property that is a integer. When I am in the Edit view, this property is used this way and it work well.
@Html.DropDownListFor(model => model.Country, new SelectList(ViewBag.Countries, "IDCountry", "Name"))
In the Details view, I only want to show the name of the country, but I don’t know how! Right now, I’m doing this but it only show the ID and I can’t find a way to give him the List so it use it as a datasource or something like that to show “Canada” instead of 42.
@Html.DisplayFor(model => model.Country)
How can this be achieved?
By using a view model of course:
and then you would populate this view model in the controller action that is supposed to render your Display view:
Now your view will be strongly typed to the view model of course:
So as you can see in ASP.NET MVC you should always be working with view models. Think in terms of what information you need to work with in a given view and the first thing you should do is define a view model. Then it’s the responsibility of the controller action that is serving the view to populate the view model. Where the values of this view model are coming from doesn’t really matter. Think of the view model as a single point of aggregation of many data sources.
As far as the views are concerned, they should be as dumb as possible. Simply work with what’s available in the view model.