2013-02-26 149 views
1

我剛剛開始使用MVC和有下面的代碼:HTML.Display()不顯示任何

@model AzureDemo.Models.User 

@{ 
    ViewBag.Title = "Interests"; 
} 

<h2>Interests</h2> 

<p> 
    @Html.ActionLink("Logout", "Logout") 
</p> 
<table> 
    <tr> 
     <th> 
      Interests 
     </th> 
    </tr> 

@foreach (var interest in Model.Interests) { 
    <tr> 
     <td> 
      @Html.Display(interest) 
     </td> 
     //Tried like this 
     <td> 
      @Html.Display("id", interest.ToString()) 
     </td> 
    </tr> 
} 

</table> 

在用戶興趣屬性僅僅是一個字符串列表。我試圖在用戶的表格中顯示每個興趣。我也嘗試在Html.Display中放入一個像「test」這樣的字符串,或者嘗試使用ToString(),但仍然沒有任何結果。

+0

你爲什麼不直接使用?像這樣:'​​@ interested' – 2013-02-26 12:10:43

+0

那工作!如果你把它作爲答案,我會接受:) – Matt 2013-02-26 13:33:07

回答

1

您可以直接使用模型項目這樣

@foreach (var interest in Model.Interests) { 
<tr> 
    <td> 
     @interest 
    </td> 
    // or this 
    <td> 
     @interest.ToString() 
    </td> 
</tr> 
} 

,或者如果您在您的視圖顯示HTML代碼,那麼這是更安全

@foreach (var interest in Model.Interests) { 
<tr> 
    <td> 
     @Html.Raw(interest) 
    </td> 
</tr> 
} 

也感謝給我這個機會;)

4

我建議你使用顯示模板,並擺脫視圖中的所有foreach循環:

@model AzureDemo.Models.User 

@{ 
    ViewBag.Title = "Interests"; 
} 

<h2>Interests</h2> 

<p> 
    @Html.ActionLink("Logout", "Logout") 
</p> 
<table> 
    <thead> 
     <tr> 
      <th> 
       Interests 
      </th> 
     </tr> 
    </thead> 
    <tbody> 
     @Html.DisplayFor(x => x.Interests) 
    </tbody> 
</table> 

,然後定義它會自動呈現的興趣收集(~/Views/Shared/DisplayTemplates/Interest.cshtml)的每個元素對應的顯示模板:

@model AzureDemo.Models.Interest 
<tr> 
    <td> 
     @Html.DisplayFor(x => x.Text) 
    </td> 
</tr> 
+0

謝謝我會試試這個,但是我已經告訴AliRiza我會接受他的回答:) – Matt 2013-02-26 14:04:29