Multiple instance of partial razor form

2019-08-10 19:55发布

问题:

I have 2 nested partial controls

User Control1:

Html.BeginRouteForm
(
   Html.RenderPartial (path of child form)
)

ChildControl:

Html.LabelFor(x=>x.FirstName,"First Name")
Html.TextBoxFor(x=>x.FirstName)
...

Problem:

I have 2 instance of this partial control on home page. When I click on Submit button of second instance, form is posted using AJAX & JQuery. Since FirstName has a required constraint, form renders back with required validation triggered for FirstName. Here comes the issue: When I click on label "First Name", cursor gets focused on First Name TextBox of first instance of partial form instead of second instance where validation triggered.

Any suggestion on how to tackle this? Thanks a lot!

回答1:

At a guess, I'd say you're the victim of a duplicate ID, because the two instances of ChildControl are likely generating the same ID string.

Unlike ASPNET, MVC appears to generate IDs "locally". In other words, nothing behind the scenes keeps track of how many "controls" are generated, which is what allows ASPNET to generate unique ids.

If so, it's an easy enough problem to solve. Just add your own ID to each instance of ChildControl, doing something like the following:

@Html.TextBox("rel_date", Model.Value.rel_date.ToSiteString(), new { @class = "date-picker", style = "width: 75px;", id = "" })

Here I'm actually suppressing the ID on a textbox I'm generating by passing in an empty ID value in the html attributes parameter of the TextBox helper call. You'd insert some ID which you know to be unique to the page.

BTW, you can quickly check to see if I'm right about the duplicate IDs by checking the generated html for the page. When it's up in IE just hit F12 (in IE9 anyway). That'll open a window which allows you to browse the html that's generating your page. You can read it to see if the ID attributes of the two textboxes are the same, which would support my theory.

Good luck!