Here is what I will 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, 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, remember to also include the using statement in the view corresponding to the location of HtmlPrefixScopeExtensions.cs, for example:
@using YourNamespace.Helpers
or add the correct namespace in Views / Web.config (this is definitely the recommended option, you only do it once!):
<namespaces> <add namespace="System.Web.Helpers" /> ...... <add namespace="YourNamespace.Helpers" /> </namespaces>
Now: the name of the fields will be, for example, "Country.Name"
Then you should have the appropriate name in your message, for example:
[HttpPost] public ActionResult SaveCountry(Country country) { // save logic return View(); }
Credits: I removed Steve Sanderson's wonderful BeginCollectionItem class
joargp
source share