2016-12-26 142 views
1

我想在視圖中用標記幫助程序替換HTML幫助程序。用標記幫助程序替換HTML幫助程序

爲此,我更換:@model IEnumerable<Person>

通過@model IList<Person>

@Html.DisplayNameFor(model => model.Name)

通過<label asp-for="@Model[0].Name"></label>

但我應該使用:@Html.DisplayFor(modelItem => item.Name)

<input asp-for="@item.Name" readonly />

它看起來不正確。

UPDATE:只是爲了澄清問題:@Html.DisplayNameFor<label asp-for都生成HTML標籤。

@Html.DisplayFor只生成文本。哪個標籤幫手可以代替它?我不想用input來顯示文字。

回答

0

當您使用IList時,您可以同時訪問屬性。

@model IList<WebApp.Models.Person> 

<input type="text" asp-for="@Model[0].Name" /> 

@foreach(var item in Model) 
{ 
    <input type="text" asp-for="@item.Name" readonly/> 

} 

,如果你使用的IEnumerable,你需要調用ToList方法不使用foreach

@model IList<WebApp.Models.Person> 
@{ 
var model2 = Model.ToList(); 
} 

<input type="text" asp-for="@model2[0].Name" /> 

@foreach(var item in Model) 
{ 
    <input type="text" asp-for="@item.Name" readonly/> 
} 
+0

問題訪問屬性是:我應該使用輸入只是爲了顯示信息?它會在html中生成文本框。 – Alexan

+0

我想要與@ Html.DisplayFor相同的結果,但使用標籤助手。 – Alexan

+0

對於顯示信息,您可以像這樣使用帶有剃鬚刀的HTML標籤。 '

    @foreach(在模型VAR項) {
  • @ item.Name
  • }
' – Ahmar