ASP.NET field identifier generation ASP.NET, partial views loaded by AJAX create unique names

We use ASP.NET MVC HTML Helpers to generate forms, so the form field names are also generated by these HTML Helpers.

Whenever I load a partial view through AJAX to my current page (for example, in a modal dialog), I run into problems if the model for this partial view contains a field that is called the same as any other field in its original form (since ASP.NET MVC generates the same identifiers).

Is there a way to show a partial view for displaying its fields with a specific prefix (so that subsequent model binding understands these prefix names)?

Currently, we renamed the fields in partial view models to “PartialDateOfBirth” so as not to interfere with the original DateOfBirth page model, but it sucks and doesn’t work if you load the same partial view several times via AJAX on the page .. .

Any solution to solve this problem?

+8
c # asp.net-mvc asp.net-mvc-4
source share
2 answers

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

+2
source share

Create your own Helper methods to pass a prefix with an identifier, this is not a lot of work.

0
source share

All Articles