在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> 
     } 

我没有得到任何的异常,并在所有(空白页)没有结果。

这是为什么?

+0

它只是'

@ item.PlaceName, @ item.PostalCode,....'(或'
@ Html.DisplayFor(m => item.PlaceName),@ Html.DisplayFor(m => item.PostalCode),....' –
+0

而且你没有使用@ Html.Display获取输出(item.PlaceName +“,”+ item.PostalCode ...',因为您的模型不包含与连接这些值所生成的名称相同的属性 –

您需要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> 
     } 
+0

Thanks Usman,first建议有效,而第二个则不行。仍然想知道为什么与@ Html.Display(item.PlaceName)我既没有例外也没有结果。 – Luke

+0

你不需要'Html.Raw()'而第二个不能工作! –

+0

当stephen在注释@ Html.Display中对其进行了扩展时,它适用于模型属性,在这里您的字符串不匹配任何模型 – Usman