Prevent user from submitting if a field is not unique in an MVC form using AJAX
You know those fields you see on forms which indicate that a value can't be used because its already used? Like a username for a membership site.
I'd like to do 开发者_如何学运维this for an MVC form via jquery. What is the recommendation for this?
You could create a JsonResult action that you can call from your javascript code. Eg
public JsonResult IsUsernameAvailable(string username) {
// return result
return Json(true);
}
And then hook it up to your username-field like so using jQuery
$("#username").blur(function() { checkAvailability($(this).val()); });
function checkAvailability(username) {
$.getJSON("/User/IsUsernameAvailable", { username: username }, function(result) {
alert("Is available: " + result);
});
}
If you are using MVC 3 there is a new Remote attribute which you can use. You specify a route or controller/action for the attribute and return "true" or "false" (or any string != "true", which could be 'result' in your case. You will get a client side validation error similar to the errors you get if a required field is left blank etc.
精彩评论