1

我正在使用 MVC4 Razor 来呈现一个简单的网页,并且想知道是否有一种简单的方法可以使用 DisplayFor 来呈现“已翻译”的值,而不是显示模型的 ID 值。

模型:

public class Property
{
    [Key]
    public int Rec_Id { get; set; }
    public string Name  { get; set; }
    public int TypeId  { get; set; }
}

public class Type
{
    public int TypeId  { get; set; }
    public string TypeName  { get; set; }
}

控制器:

public ActionResult Index()
{
    PropertyContext db = new PropertyContext();
    Property model = db.Property.Find(94284);
    ViewBag.cmbType = db.Type.ToList();
    return View(model);
}

看法

<div class="display-field">
    @Html.DisplayFor(ViewBag.Type => ViewBag.Type.Find(model.Type).TypeName)
</div>
4

1 回答 1

0

我建议您使用视图模型,因为您的域模型不适合您需要显示类型名称的视图的要求:

public class MyViewModel
{
    public int RecId { get; set; }
    public string Name  { get; set; }
    public string TypeName { get; set; }
}

然后让您的控制器操作通过执行 INNER JOIN 填充此视图模型并将其传递给视图:

public ActionResult Index()
{
    using (PropertyContext db = new PropertyContext())
    {
        var query = 
            from prop in db.Property.Find(94284)
            join type in db.Type on prop.TypeId equals type.TypeId
            select new MyViewModel
            {
                RecId = prop.Rec_Id,
                Name = prop.Name,
                TypeName = type.TypeName
            };

        var viewModel = query.FirstOrDefault();
        return View(viewMode);
    }
}

最后,您的视图将被强输入到视图模型中,并且您将拥有要显示的所有必要信息:

@model MyViewModel
...
<div class="display-field">
    @Html.DisplayFor(model => model.TypeName)
</div>
于 2013-02-17T16:14:45.477 回答