![](/img/trans.png)
[英]Html.TextBoxFor NullReferenceException using Razor syntax
[英]Using @Html.TextBoxFor with ViewModel
一個簡單的問題:
因此,我正在開發一個小型MVC / C#應用程序,並且正在使用ViewModel將數據傳遞到視圖。 ViewModel實際上是3個模型的組合。
我的模特:
public class Sourcing_ProfileSourcingAreas
{
public string Area { get; set; }
public string Details { get; set; }
}
public class DefCountry
{
public string CountryName { get; set; }
public string CountryCode { get; set; }
}
我的ViewModel:
public class SourcingIndex
{
public List<DefCountry> CountryLst { get; set; }
public List<Sourcing_ProfileSourcingAreas> AreaLst { get; set; }
}
在我看來,我將此行放在@model SourcingIndex
的頂部,以聲明我將使用此ViewModel。
我還可以輕松地通過使用foreach
循環來指定要顯示的模型,例如:
@foreach (Sourcing_ProfileSourcingAreas area in Model.AreaLst)
{
<tr>
<td>@area.Area</td>
<td>@area.Details</td>
</tr>
}
和
@foreach (DefCountry ctry in Model.CountryLst)
{
<option>@ctry.CountryName</option>
}
但是,我無法創建@Html.TextBox
並將其分配給模型中的特定屬性!
如果可能的話,我希望它像這樣: @Html.TextBoxFor(model => model.AreaLst.Area)
謝謝
關於Razor有點古怪。 如果嘗試在foreach
循環中訪問對象,則很難確定模型在哪里。 您需要使用以下語法:
@for (int x = 0; x < Model.CountryLst.Count(); x++)
{
@Html.TextBoxFor(t => t.CountryLst[x].CountryName)
}
這應該產生一個類似的輸入
<input name="countryLst[1].CountryName"/>
@for(var i = 0; i < Model.CountryLst.Count(); i++)
{
<text>@Html.TextBoxFor(p=>Model.CountryLst[i].CountryCode)</text>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.