我对MVC很陌生,但一直在稳步前进,但我最近遇到了一个问题,尽管我在类似主题上阅读过类似的帖子,但我似乎无法克服这个问题。
我有一个如下的模型(简化为简洁)
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Address Address { get; set; }
我有一个强类型视图如下:
@model JFS.Data.Model.Supplier
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Supplier Address</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Address.AddressLine1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address.AddressLine1)
@Html.ValidationMessageFor(model => model.Address.AddressLine1)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Address.Country)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Address.Country)
@Html.ValidationMessageFor(model => model.Address.Country)
</div>
</fieldset>
我在Country字段中有一个共享的EditorTemplate,如下所示:
@model JFS.Data.Model.Address
@using System.Globalization
@Html.DropDownListFor(o => o.Country, GetCountries(Model), "Please select")
@functions
{
private static IEnumerable<SelectListItem> GetCountries(object country)
{
var regions = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
.Select(cultureInfo => new RegionInfo(cultureInfo.LCID))
.OrderBy(r => r.EnglishName)
.Distinct()
.ToList();
return new SelectList(regions, "TwoLetterISORegionName", "EnglishName", country);
}
}
我理解这个问题,但不确定如何最好地克服它,任何建议都会非常感激。
答案 0 :(得分:2)
虽然你的特定场景已经被@ProNotion回答了,但是在你将null传递给视图或模板之前我遇到过这个问题。它可能会帮助其他人这样做。
答案 1 :(得分:1)
在主视图中替换:
@Html.EditorFor(model => model.Address.Country)
使用:
@Html.EditorFor(model => model.Address)
顺便说一下,如果您正在为Address
模型编写共享编辑器模板,您可能希望在此模板中包含其他属性,例如AddressLine1
。
答案 2 :(得分:1)
您只需传递Address
属性:
@Html.EditorFor(model => model.Address)
您正在尝试传递Address
的{{1}}属性,而类型的要求为string
。