gpt4 book ai didi

validation - 显示远程验证成功响应的自定义消息

转载 作者:行者123 更新时间:2023-12-04 02:08:43 25 4
gpt4 key购买 nike

我在注册 asp.net mvc 3 应用程序 (C#) 期间使用远程验证来检查用户名的可用性。

我使用 MVC 远程属性验证作为:

[Remote("IsUserNameAvailable", "User")]
public string UserName { get; set; }

我需要在两个条件下显示消息:
  • 显示错误消息“用户名不可用” - 失败条件
  • 显示成功消息“用户名可用” - 成功条件

  • 我能够在没有任何问题的情况下显示失败条件的消息,例如:
    return Json("Username not available", JsonRequestBehavior.AllowGet);

    但是对于成功条件,我需要在响应中发送 true(而不是自定义消息),如下所示:
     return Json(true, JsonRequestBehavior.AllowGet);

    如何为远程验证的成功条件显示自定义消息?

    最佳答案

    看到这个链接...
    here

    实现此目的的一种方法是从验证操作中添加自定义 HTTP 响应 header :

    public ActionResult IsUserNameAvailable(string username)
    {
    if (IsValid(username))
    {
    // add the id that you want to communicate to the client
    // in case of validation success as a custom HTTP header
    Response.AddHeader("X-ID", "123");
    return Json(true, JsonRequestBehavior.AllowGet);
    }

    return Json("The username is invalid", JsonRequestBehavior.AllowGet);
    }

    现在在客户端上,我们显然有一个标准表单和一个用于用户名的输入字段:
    @model MyViewModel
    @using (Html.BeginForm())
    {
    @Html.EditorFor(x => x.UserName)
    @Html.ValidationMessageFor(x => x.UserName)
    <button type="submit">OK</button>
    }

    现在拼图的最后一部分是将完整的处理程序附加到用户名字段上的远程规则:
    $(function () {
    $('#UserName').rules().remote.complete = function (xhr) {
    if (xhr.status == 200 && xhr.responseText === 'true') {
    // validation succeeded => we fetch the id that
    // was sent from the server
    var id = xhr.getResponseHeader('X-ID');

    // and of course we do something useful with this id
    alert(id);
    }
    };
    });

    关于validation - 显示远程验证成功响应的自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6422988/

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