请在成功响应东西在MVC远程验证 [英] Do something on success response for remote validation in mvc

查看:92
本文介绍了请在成功响应东西在MVC远程验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用远程验证登记我的asp.net MVC 3广告应用程式(C#)期间检查用户名的可用性。

I am using remote validation to check the availability of username during registration for my asp.net mvc 3 applicaion (C#).

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

I am using MVC remote Attribute validation as:

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

当我回到这一点:

return Json(true, JsonRequestBehavior.AllowGet);

然后我要执行类似设置隐藏字段的值,这是自行动回报或显示绿色图标的图像。我想也与真正的回报ID。

Then I want to perform something like set the hidden field value, which is return from action or show green icon image. And i want to also return ID with true.

如何实现这个东西呢?

在短,我想要做的成功的东西。

In short, I want to do something on success.

推荐答案

实现方法之一就是从验证动作添加自定义HTTP响应头:

One way to achieve that is to add a custom HTTP response header from the validation action:

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);
}

现在在客户端上我们显然有一个标准的形式,为用户名输入字段:

Now on the client we obviously have a standard form and an input field for the username:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.UserName)
    @Html.ValidationMessageFor(x => x.UserName)
    <button type="submit">OK</button>
}

现在拼图的最后一块就是附加一个完整处理程序上的用户名的远程规则现场:

and now the last piece of the puzzle is to attach a complete handler to the remote rule on the username field:

$(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);
        }
    };
});

这篇关于请在成功响应东西在MVC远程验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆