asp.net-mvc - 如何在 Razor MVC 3 中显示属性的文本而不是 ID

标签 asp.net-mvc data-binding razor drop-down-menu

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

我有一个模型,该模型包含一个整数“Country”属性。当我在“编辑” View 中时,以这种方式使用此属性并且效果很好。

@Html.DropDownListFor(model => model.Country, new SelectList(ViewBag.Countries, "IDCountry", "Name"))   

在详细信息 View 中,我只想显示国家/地区的名称,但我不知道如何!现在,我正在这样做,但它只显示 ID,而且我找不到给他列表的方法,因此它使用它作为数据源或类似的东西来显示“加拿大”而不是 42。

@Html.DisplayFor(model => model.Country)

如何实现这一目标?

最佳答案

How can this be achieved?

当然是使用 View 模型:

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

然后您将在应该呈现您的显示 View 的 Controller 操作中填充此 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);
}

现在您的 View 当然将被强类型化到 View 模型:

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

正如您在 ASP.NET MVC 中看到的,您应该始终使用 View 模型。考虑在给定 View 中需要使用哪些信息,您应该做的第一件事就是定义 View 模型。然后, Controller 操作负责为 View 提供服务以填充 View 模型。这个 View 模型的值来自哪里并不重要。将 View 模型视为许多数据源的单点聚合。

就观点而言,他们应该尽可能愚蠢。只需使用 View 模型中可用的内容即可。

关于asp.net-mvc - 如何在 Razor MVC 3 中显示属性的文本而不是 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14305818/

相关文章:

c# - 我可以在.net MVC 中使用FromBody 和FromUri 吗?

Android fragment DataBinding 非空 getter 返回 null

c# - 如何在 Razor View 中指定全局 MVC 布局而不指定布局路径

asp.net-mvc-3 - ASP.NET MVC : Html. EditorFor 和多行文本框

asp.net-mvc - 删除 Microsoft BotFramework iFrame 中的图像上传按钮

c# - 为什么 InProc session 模式不需要序列化

返回 void 的 ASP.Net MVC Controller 操作

.net - 绑定(bind)自动分离的情况

java - 数据绑定(bind) "error: cannot find symbol class Models"

javascript - 有没有办法用 javascript 填充 html 中的数据文本字段?