在foreach循环中使用Html.Display和Html.DisplayFor在剃刀视图中显示复合模型项目
问题描述:
我对此有点困惑。 我穿越到视图页面视图模型包含两个属性:在foreach循环中使用Html.Display和Html.DisplayFor在剃刀视图中显示复合模型项目
public class UserProfileViewModel
{
public ApplicationUser userProfile { get; set; }
public AddressViewModel userAddress { get; set; }
}
的AddressViewModel本身包含一个列表,其项目我想查看页面中显示:
public class AddressViewModel
{
public int ID { get; set; }
......
public virtual List<GeoData> GeoDataList { get; set; }
}
呼我尝试这对Wiew页
@model MySite.ViewModels.UserProfileViewModel
...
@foreach (var item in Model.userAddress.GeoDataList)
{
<dd>
@Html.DisplayFor(modelitem => item.PlaceName)
</dd>
}
我得到正确的结果exptected 但是,当我试图表明的复合结果,我需要
@foreach (var item in Model.userAddress.GeoDataList)
{
<dd>
@Html.DisplayFor(modelitem => (item.PlaceName + ", " + item.PostalCode + ", " + item.Latitude + ", " + item.Longitude))
</dd>
}
我得到以下异常:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
而当我试试这个:
@foreach (var item in Model.userAddress.GeoDataList)
{
<dd>
@Html.Display(item.PlaceName + ", " + item.PostalCode + ", " + item.Latitude + ", " + item.Longitude)
</dd>
}
我没有得到任何的异常,并在所有(空白页)没有结果。
这是为什么?
答
您需要GeoData类的显示模板。显示模板是控制器文件夹或Shared中DisplayTemplates子文件夹中称为GeoData.cshtml的局部视图。你的地理数据将是这样
@model MySite.ViewModels.GeoData @ Model.PlaceName,@ Model.PostalCode,@ Model.Latitude,@ Model.Longitude
和你的用户配置页面的代码一样
<dd>
@Html.DisplayFor(modelitem => item)
</dd>
答
可以使用@Html.Raw
它显示的结果没有任何HTML编码
@foreach (var item in Model.userAddress.GeoDataList)
{
<dd>
@Html.Raw(item.PlaceName + ", " + item.PostalCode + ", " + item.Latitude + ", " + item.Longitude)
</dd>
}
它只是'
而且你没有使用@ Html.Display获取输出(item.PlaceName +“,”+ item.PostalCode ...',因为您的模型不包含与连接这些值所生成的名称相同的属性 –