Show user message for remote verification response

I use remote verification to check the username availability during registration for my asp.net mvc 3 (C #) application.

I use MVC remote attribute verification as:

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

I need to show the message in two conditions:

  • Show Error "Username Unavailable" - Failed Status
  • Show Success Message "Available Username" - Success Status

I can show a failure status message without any problems, for example:

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

But for the success condition, I need to send true in the response (not with a custom message) as:

  return Json(true, JsonRequestBehavior.AllowGet); 

How can I show a custom message to check the status of a remote check?

+4
source share
2 answers

see this link ... here

One way to achieve this 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 the standard form and 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 the full handler to the deleted rule in 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); } }; }); 
+2
source

Can you return an object (which will be serialized for Json)?

For instance:

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

Then you can analyze this in the view.

In addition, if you do so, but the username is NOT available, you can add a few suggested usernames.

eg.

 // 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); 
0
source

All Articles