这是我要做的:
在您的项目中将其另存为 HtmlPrefixScopeExtensions.cs
public static class HtmlPrefixScopeExtensions
{
public static IDisposable BeginPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
internal class HtmlFieldPrefixScope : IDisposable
{
internal readonly TemplateInfo TemplateInfo;
internal readonly string PreviousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
TemplateInfo = templateInfo;
PreviousHtmlFieldPrefix = TemplateInfo.HtmlFieldPrefix;
TemplateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose()
{
TemplateInfo.HtmlFieldPrefix = PreviousHtmlFieldPrefix;
}
}
}
然后改变你的观点,例如:
<div class="content">
<div>
@Html.EditorFor(model => model.Name)
</div>
<div>
@Html.EditorFor(model => model.Population)
</div>
</div>
至:
@using (Html.BeginPrefixScope("Country"))
{
<div class="content">
<div>
@Html.EditorFor(model => model.Name)
</div>
<div>
@Html.EditorFor(model => model.Population)
</div>
</div>
}
最后但同样重要的是,不要忘记在与 HtmlPrefixScopeExtensions.cs 的位置匹配的视图中包含 using 语句,例如:
@using YourNamespace.Helpers
或将正确的命名空间添加到 Views/Web.config (这是迄今为止推荐的选项,您只需执行一次!):
<namespaces>
<add namespace="System.Web.Helpers" />
......
<add namespace="YourNamespace.Helpers" />
</namespaces>
现在:字段名称将是例如“Country.Name”
然后,您的帖子中必须有匹配的名称,例如:
[HttpPost]
public ActionResult SaveCountry(Country country)
{
// save logic
return View();
}
致谢:我剥离了 Steve Sanderson 精彩的 BeginCollectionItem 类