How to show the text of a property instead of the ID in Razor MVC 3

这一生的挚爱 提交于 2020-05-30 06:04:28

问题


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?


回答1:


How can this be achieved?

By using a view model of course:

public class CountryViewModel
{
    public int CountryId { get; set; }
    public string CountryName { get; set; }
}

and then you would populate this view model in the controller action that is supposed to render your Display view:

public ActionResult Display(int id)
{
    Country country = ... go and fetch from your db the corresponding country from the id

    // Now build a view model:
    var model = new CountryViewModel();
    model.CountryId = country.Id;
    model.CountryName = country.Name;

    // and pass the view model to the view for displaying purposes
    return View(model);
}

Now your view will be strongly typed to the view model of course:

@model CountryViewModel
@Html.DisplayFor(x => x.CountryName)

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.



来源:https://stackoverflow.com/questions/14305818/how-to-show-the-text-of-a-property-instead-of-the-id-in-razor-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!