MVC显示来自另一个表的外键

时间:2013-05-09 12:58:45

标签: asp.net-mvc

控制器:

public ActionResult Details(int id)
    {
        ViewBag.AccountType = new BusinessLayer.AccountTypeManager().GetAccountTypes();
        return View(new BusinessLayer.AccountManager().getAccount(id));
    }

查看:

<div class="display-label">Account Type</div>
<div class="display-field">@Html.DisplayFor(modelItem => modelItem.AccountType)</div><br />

此当前视图显示AccountType ID。如何显示ViewBag.AccountType(IEnumerable)传递的AccountType名称

1 个答案:

答案 0 :(得分:0)

类似于以下内容

<div class="display-label">Account Type</div>
<div class="display-field">@Html.DisplayFor(modelItem => modelItem.AccountType)</div>
@{
    var TypeNames = ViewBag.AccountType as IEnumerable<string>;

    foreach(var item in TypeNames)
    {
        <div>item</div>
    }
}

模式优雅的方式

public class AccountTypeVewModel
{
    public IEnumerable<string> typeNames { get; set; }
    public Account account { get; set; }
}

控制器

public ActionResult Details(int id)
{
    AccountTypeVewModel model = new AccountTypeVewModel();
    model.typeNames = new BusinessLayer.AccountTypeManager().GetAccountTypes();
    model.account = new BusinessLayer.AccountManager().getAccount(id);
    return View(model);
}

视图

<div class="display-label">Account Type</div>
<div class="display-field">@Html.DisplayFor(modelItem => modelItem.account.AccountType)</div>
@{
    foreach(var item in Model.typeNames)
    {
        <div>item</div>
    }
}