gpt4 book ai didi

validation - Ajax.BeginForm-显示验证错误

转载 作者:行者123 更新时间:2023-12-03 08:07:18 26 4
gpt4 key购买 nike

在VS2008中使用MVC项目模板(开箱即用),我注意到以下几点:

  • 这是指定Register.aspx表单的方式。
    <% using (Html.BeginForm()) { %>
  • 选择“注册”按钮而不提供任何帐户信息将显示此信息。帐户创建失败。请更正错误,然后重试。

    •您必须指定一个用户名。
    •您必须指定一个电子邮件地址。
    •您必须指定6个或更多字符的密码。
  • 我将Register.aspx表单更改为此。
    <% using (Ajax.BeginForm("Register", new AjaxOptions { HttpMethod = "Post" })) { %>
  • 选择“注册”按钮而不提供帐户信息不会显示任何错误。

  • 问题:使用Ajax.BeginForm时如何显示错误文本?

    最佳答案

    为了成功应用ajax表单提交,您将必须修改Register操作和 View 。默认情况下,如果发生错误,此操作仅返回关联的register.aspx View 。第一步是将验证摘要放入部分用户控件中:

    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 View 中:
    <div id="validationSummary">
    <% Html.RenderPartial("ValidationSummary"); %>
    </div>

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

    最后,您修改Register Action :
    [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();
    }
    }

    如果默认情况下注册成功,则Register操作仅重定向到Home/Index。您还必须修改此位,因为在执行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 ?



    为了实现这一点,您需要将表单的内容放入局部 View 中:
    <% using (Ajax.BeginForm(
    "register",
    null,
    new AjaxOptions {
    HttpMethod = "POST",
    UpdateTargetId = "myForm"
    },
    new {
    id = "myForm"
    })) { %>
    <% Html.RenderPartial("RegisterForm"); %>
    <% } %>

    并在您的register Action 中呈现正确的部分:
    if (Request.IsAjaxRequest())
    {
    return PartialView("RegisterForm");
    }
    else
    {
    return View();
    }

    关于validation - Ajax.BeginForm-显示验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1585245/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com