Do something on success response for remote validation in mvc

久未见 提交于 2019-12-31 14:28:00

问题


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

I am using MVC remote Attribute validation as:

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

When I return this:

return Json(true, JsonRequestBehavior.AllowGet);

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.

How to achieve this things ?

In short, I want to do something on success.


回答1:


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


来源:https://stackoverflow.com/questions/10702914/do-something-on-success-response-for-remote-validation-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!