ASP.NET MVC 在View中获取Model以外的关系属性

问题描述

有一个帐户和帐户类型表,如下图所示:

image

我主要是想在View中除了绑定Account的数据,同时还想把AccountType的名字也一起绑定。

我们知道在View中只有@model IEnumerable<Account> 的内容,因为只有对应的AccountTypeID得不到他AccountTypeName

解决办法

方法一:

重新定义一个Action

public ActionResult GetAccountTypeNameByAccountTypeID(Guid accountTypeID)
        {
            return Content(accountTypeService.GetAccountType(accountTypeID).AccountTypeName);
        }

在View中直接包括该Action的内容就行了。

@{
  Html.RenderAction("GetAccountTypeNameByAccountTypeID", new { AccountTypeID = item.AccountTypeID });
  }

方法二:

在Account中增加一个AccountType的属性。在构造Account时就把AccountType给构造完成,在View中调用时直接就可以@item.AccountType.AccountTypeName

原文地址:https://www.cnblogs.com/jiguixin/p/3007519.html