I'm trying to implement a .NET Custom Validator that uses $.ajax to query a WebMethod on the same page and return a boolean value to indicate whether the result is true or false.
The WebMethod I'm using is really simple
[WebMethod()]
public static bool IsPromoValid(string code)
{
string promoCode = "ABCDEFG";
bool result = code.ToLower() == promoCode.ToLower();
return result;
}
The CustomValidator looks like this
<asp:CustomValidator ID="cvPromoCode" Display="None" ControlToValidate="txtPromoCode" runat="server" ClientValidationFunction="validatePromo"
ErrorMessage="The promo code you entered is incorrect" OnServerValidate="ValidatePromoCode" />
And the simple $.ajax() ClientValidation function
function validatePromo(src, args) {
$.ajax({
type: "POST",
url: "Register.aspx/IsPromoValid",
data: "{'code': '" + args.Value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
args.IsValid = msg.d;
}
});
}
The problem is that the page validates instantly and doesn't actually wait for the ajax call to finish. If there are any other errors on the page, it shows the Validation Summary with them, but never shows the error message from the Custom Validator.
I can see the AJAX call being made in Firebug, and it returs the right response (in this case true or false)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…