4

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

我将 MVC 远程属性验证用作:

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

我需要在两个条件下显示消息:

  1. 显示错误消息“用户名不可用” - 失败条件
  2. 显示成功消息“用户名可用” - 成功条件

我能够显示失败条件的消息,而不会出现任何问题,例如:

return Json("Username not available", JsonRequestBehavior.AllowGet);

但是对于成功条件,我需要发送 true 作为响应(而不是自定义消息):

 return Json(true, JsonRequestBehavior.AllowGet);

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

4

2 回答 2

2

看到这个链接...... 在这里

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

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);
    }
};
});
于 2012-05-23T11:29:52.073 回答
0

Are you able to return an object (which will be serialised to Json)?

Such as:

var answer = new { success = true, message = "Username available" };
return Json(answer, JsonRequestBehavior.AllowGet);

Then you can parse this in the view.

Also, if you do it this way, but the username is NOT available, you could add a few suggested usernames too.

e.g.

// pretend they chose "dave"
List<string> alternativeNames = new List<string>() { "dave1", "dave2" };
var answer = new { success = false, message = "Username not available", alternatives = alternativeNames };
return Json(answer, JsonRequestBehavior.AllowGet);
于 2011-06-21T09:24:36.993 回答