问题
I have a scenario where I have a login form next to a registration form, as the login form is a permanent fixture (until much further development), and sometimes registration as the main content coincides with this login form.
Now we enter the twilight zone: Both forms have different actions on different controllers, but they share two things in common, being they both have a ValidationSummary
, and they both have a field called UserName
. If I cause a server side validation error, e.g. when the user hasn't ticked 'Accept terms of use', using
ModelState.AddModelError("", "You must accept the Terms and Conditions to become a member.");
the error is displayed in the validation summaries of both forms, and the new user name, i.e. the user trying to register, is displayed in the UserName
field on both forms. The forms don't even share a common view model type, let alone instance. All I can ask to make this properly a question is WTF?
回答1:
If your html elements have the same Id you might expect this kind of behaviors. I think that the easiest solution for this is to rename your login username id name into a more explicit one like LoginUserName. this way you are not mixing two different things.
Second, I suggest you (if you haven't done so) to encapsulate your login functionality into a separate form (if that applies) because you would be sending the whole page, including use cases that don't apply to a login action.
回答2:
Seems like the issue with same client input names. Take a look at BindAttribute.Prefix and TemplateInfo.HtmlFieldPrefix. By using them you can generate different client ids and names for those different actions and models, and the problem will probably be solved. HtmlFieldPrefix
is used for appending prefix for client generated ids, and the Bind.Prefix
is used for binding back client form values generated with HtmlFieldPrefix
. Both of them are set in controller action.
来源:https://stackoverflow.com/questions/6642596/mvc3-form-binding-duplicated-across-two-neighbouring-html-forms