Asp.net-Mvc-4
複雜模型上的 MVC Html.DisplayNameFor
我有一個複雜類型的模型,即使用者/地址/地址列表
public class User{ public List<Address> Addresses{get;set;} }在我的視圖中,我正在顯示這個
<fieldset><legend>@Html.DisplayNameFor(model=>model.Addresses)</legend> <table> <tr> <th> @Html.DisplayNameFor(m => Model.Addresses.Street) </th> <th> @Html.DisplayNameFor(model => model.Addresses.City) </th> <th> @Html.DisplayNameFor(model => model.Addresses.State) </th> </tr> @foreach (var item in Model.Addresses) { <tr> <td> @Html.DisplayFor(m => item.Street) </td> <td> @Html.DisplayFor(m => item.City) </td> <td> @Html.DisplayFor(m => item.State) </td> </tr> } </table></fieldset>DisplayNameFor Street/City/State 不起作用。
在子對像上獲取 DisplayNameFor 的正確方法是什麼?
蒂亞傑
我變了
@Html.DisplayNameFor(m => Model.Addresses.Street)至
@Html.DisplayNameFor(m => Model.Addresses.FirstOrDefault().Street)不要使用
@Html.DisplayNameFor(m => Model.Addresses[0].Street),因為如果您需要編輯第一行,您將無法使用這種方式。現在一切都按預期工作。
您還可以使用 Linq 來避免索引錯誤。我用這是我的程式碼 -
@Html.DisplayNameFor(m => Model.Addresses.first().Street)以下錯誤消失了。
Cannot apply indexing with [] to an expression of type 'System.Data.Objects.DataClasses.EntityCollection<Address>但是最好使用以下語句直接使用名稱
@Html.DisplayName("Street")