Ajax.BeginForm - 显示验证错误
在 VS2008 中使用 MVC 项目模板(开箱即用),我注意到以下内容:
这是如何指定 Register.aspx 表单的。
<% using (Html.BeginForm()) { %>;
选择“注册”按钮而不提供任何帐户信息会显示这一点。帐户创建失败。请更正错误并重试。
• 您必须指定用户名。
• 您必须指定电子邮件地址。
• 您必须指定 6 个或更多字符的密码。我将 Register.aspx 表单更改为此。
<% using (Ajax.BeginForm("Register", new AjaxOptions { HttpMethod = "Post" })) { %>;
选择“注册”按钮而不提供帐户信息不会显示任何错误。
问题:使用 Ajax.BeginForm 时如何显示错误文本?
Using the MVC project template in VS2008 (out of the box) I noticed the following:
Here is how the Register.aspx form is specified.
<% using (Html.BeginForm()) { %>
Selecting the Register button without supplying any account info shows this. Account creation was unsuccessful. Please correct the errors and try again.
• You must specify a username.
• You must specify an email address.
• You must specify a password of 6 or more characters.I changed the Register.aspx form to this.
<% using (Ajax.BeginForm("Register", new AjaxOptions { HttpMethod = "Post" })) { %>
Selecting the Register button without supplying an account info shows no errors.
Question: How do I get the error text to display when using Ajax.BeginForm ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要成功应用 ajax 表单提交,您必须修改注册操作和视图。默认情况下,如果出现错误,此操作仅返回关联的 register.aspx 视图。第一步是将验证摘要放入部分用户控件中:
ValidationSummary.ascx:
然后将此部分包含在 Register.aspx 视图中:
最后修改 Register 操作:
如果默认情况下注册成功,则使用 Register 操作只是重定向到主页/索引。您还必须修改这一点,因为当您执行 ajax 请求时,重定向将不起作用。您可以使用相同的方式测试是否异步调用该操作并返回一些表明注册成功的文本。此文本将显示在与验证错误相同的
div
内。更新:
为了实现这一点,您需要将表单的内容放入部分视图中:
并在您的注册操作中呈现正确的部分:
To successfully apply ajax form submission you will have to modify the Register action and the views. By default, in case of error, this action just returns the associated register.aspx view. The first step would be to put the validation summary inside a partial user control:
ValidationSummary.ascx:
Then you include this partial inside the Register.aspx view:
And finally you modify the Register action:
In case the registration succeeds by default the Register action just redirects to Home/Index. You will have to modify this bit as well, because as you are performing an ajax request the redirection won't work. The same way you could test if you are invoking the action asynchronously and return some text that will indicate that the registration was successful. This text will be displayed inside the same
div
as the validation errors.UPDATE:
In order to achieve this you need to put the contents of your form inside a partial view:
And in your register action render the correct partial: