如何在Razor MVC 3中显示属性文本而不是ID [英] How to show the text of a property instead of the ID in Razor MVC 3

查看:96
本文介绍了如何在Razor MVC 3中显示属性文本而不是ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这很简单,但在stackoverflow或google上搜索时却找不到好词.

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"))   

在详细信息"视图中,我只想显示国家/地区的名称,但是我不知道如何显示!现在,我正在执行此操作,但是它只显示ID,而且我找不到找到他的列表的方法,因此它将其用作数据源或类似的方法来显示加拿大"而不是42.

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:

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)

因此,正如您在ASP.NET MVC中所看到的那样,您应该始终在使用视图模型.考虑在给定视图中需要使用哪些信息,并且应该做的第一件事就是定义视图模型.然后,负责操作视图的控制器操作负责填充视图模型.这个视图模型的值来自哪里并不重要.将视图模型视为许多数据源的单个聚合点.

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.

这篇关于如何在Razor MVC 3中显示属性文本而不是ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆