MVC3 表单绑定在两个相邻的 html 表单之间重复
我有一个场景,在注册表旁边有一个登录表单,因为登录表单是永久固定装置(直到进一步开发),有时注册作为主要内容与此登录表单一致。
现在我们进入模糊地带:两种表单在不同的控制器上有不同的操作,但它们有两个共同点,即它们都有一个 ValidationSummary
,并且它们都有一个名为 UserName< 的字段/代码>。如果我导致服务器端验证错误,例如当用户没有勾选“接受使用条款”时,使用
ModelState.AddModelError("", "You must accept the Terms and Conditions to become a member.");
错误会显示在两种表单的验证摘要中,并且新用户名(即尝试注册的用户),显示在两种表单的UserName
字段中。这些表单甚至不共享通用的视图模型类型,更不用说实例了。为了让这个问题成为一个正确的问题,我所能要求的就是WTF?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎是相同客户端输入名称的问题。看一下 BindAttribute.Prefix和 TemplateInfo.HtmlFieldPrefix。通过使用它们,您可以为这些不同的操作和模型生成不同的客户端 ID 和名称,并且问题可能会得到解决。
HtmlFieldPrefix
用于为客户端生成的 id 附加前缀,Bind.Prefix
用于绑定回使用HtmlFieldPrefix
生成的客户端表单值。两者均在控制器动作中设置。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 theBind.Prefix
is used for binding back client form values generated withHtmlFieldPrefix
. Both of them are set in controller action.如果您的 html 元素具有相同的 Id,您可能会期望这种行为。我认为最简单的解决方案是将您的登录用户名 ID 名称重命名为更明确的名称,例如 LoginUserName。这样你就不会混合两种不同的东西。
其次,我建议您(如果您还没有这样做)将登录功能封装到单独的表单中(如果适用),因为您将发送整个页面,包括不适用于登录操作的用例。
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.