Here's what I would do:
Save this as HtmlPrefixScopeExtensions.cs in your project
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;
}
}
}
Then change your view from for example:
<div class="content">
<div>
@Html.EditorFor(model => model.Name)
</div>
<div>
@Html.EditorFor(model => model.Population)
</div>
</div>
To:
@using (Html.BeginPrefixScope("Country"))
{
<div class="content">
<div>
@Html.EditorFor(model => model.Name)
</div>
<div>
@Html.EditorFor(model => model.Population)
</div>
</div>
}
Last but not least, don't forget to either include a using statement in the view matching the location of HtmlPrefixScopeExtensions.cs, for example:
@using YourNamespace.Helpers
or add the correct namespace to Views/Web.config (this is by far the recommended option, you only do it once!):
<namespaces>
<add namespace="System.Web.Helpers" />
......
<add namespace="YourNamespace.Helpers" />
</namespaces>
Now: the name of fields will be for example "Country.Name"
You must then have matching name in your post e.g.:
[HttpPost]
public ActionResult SaveCountry(Country country)
{
// save logic
return View();
}
Credits: I stripped down Steve Sanderson's wonderful BeginCollectionItem class