加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ajax.BeginForm – 显示验证错误

发布时间:2020-12-16 01:34:43 所属栏目:百科 来源:网络整理
导读:在VS2008(开箱即用)中使用MVC项目模板我注意到以下几点: 这里是如何指定Register.aspx表单. % using (Html.BeginForm()) { % 选择注册按钮而不提供任何帐户信息显示此.帐户创建失败.请更正错误,然后重试. ?您必须指定一个用户名. ?您必须指定一个电子邮件地
在VS2008(开箱即用)中使用MVC项目模板我注意到以下几点:

>这里是如何指定Register.aspx表单.

<% using (Html.BeginForm()) { %>

>选择注册按钮而不提供任何帐户信息显示此.帐户创建失败.请更正错误,然后重试.

?您必须指定一个用户名.
?您必须指定一个电子邮件地址.
?您必须指定6个或更多字符的密码.
>我把Register.aspx表单改成了这个.

<% using (Ajax.BeginForm("Register",new AjaxOptions { HttpMethod = "Post" })) { %>

>选择注册按钮而不提供帐户信息显示没有错误.

问题:如何在使用Ajax.BeginForm时获取错误文字?

要成功应用ajax表单提交,您将不得不修改注册操作和视图.默认情况下,如果发生错误,此操作将返回相关的register.aspx视图.第一步是将验证摘要放在部分用户控件中:

ValidationSummary.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.ValidationSummary("Account creation was unsuccessful. Please correct the errors and try again.") %>

然后你将这个部分包含在Register.aspx视图中:

<div id="validationSummary">
    <% Html.RenderPartial("ValidationSummary"); %>
</div>

<% using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST",UpdateTargetId = "validationSummary" })) { %>
    FORM CODE HERE
<% } %>

最后修改注册操作:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Register(string userName,string email,string password,string confirmPassword)
{
    // ... skipped content for clarity

    // If we got this far,something failed,redisplay form
    if (Request.IsAjaxRequest())
    {
        // If an ajax request was made return only the validation errors 
        // instead of the whole page
        return PartialView("ValidationSummary");
    }
    else
    {
        return View();
    }
}

如果注册成功,默认情况下注册操作只是重定向到主页/索引.您也必须修改此位,因为正在执行ajax请求时,重定向将无法正常工作.同样的方式,您可以测试是否异步调用操作,并返回一些表示注册成功的文本.此文本将显示在与验证错误相同的div内.

更新:

One final question – Instead of the
bullet list of error messages,how do
I get each controls error message to
render next to the control using the
Html.ValidationMessage(“….”) method
?

为了实现这一点,您需要将表单的内容放在部分视图中:

<% using (Ajax.BeginForm(
    "register",null,new AjaxOptions { 
        HttpMethod = "POST",UpdateTargetId = "myForm" 
    },new { 
        id = "myForm" 
    })) { %>
     <% Html.RenderPartial("RegisterForm"); %>
<% } %>

在你的注册操作中,渲染正确的部分:

if (Request.IsAjaxRequest())
{
    return PartialView("RegisterForm");
}
else
{
    return View();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读