问题
I'm trying to use the jQuery Validator plugin with WebForms. Here's my jQuery code:
$("input[id$=FromZip]").rules('add', {
required: true,
postalCode: true,
remote: {
url: "shipping companies.aspx/ValidatePostalCode",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: "{'postalCodeToValidate': '" + $("input[id$=FromZip]").val() + "'}",
dataFilter: function(data) { return (JSON.parse(data)).d; }
},
messages: {
required: '"From" zip code is required.',
postalCode: 'Invalid "From" zip code',
remote: 'The "From" zip code was not found in the database.'
}
});
The problem with this is that the val()
always returns empty, so the value is always being flagged as false. I tried wrapping it in a function call, like so:
remote: function() {
var r = {
url: "shipping companies.aspx/ValidatePostalCode",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
data: "{'postalCodeToValidate': '" + $("input[id$=FromZip]").val() + "'}",
dataFilter: function(data) { return (JSON.parse(data)).d; }
}
}
Except now the WebMethod isn't being called at all and no Ajax request is being made, while before (without the var r = {}
stuff) the call was being made but passing empty data instead of the value from the textbox. I've been trying to figure this out for the better part of a day now.
Any suggestions?
回答1:
You can write your remote function like that
remote: function() {
var value = $('#FromZip').val();
var r = {
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'postalCodeToValidate': value }),
type: 'POST',
dataType: 'json',
url: 'shipping companies.aspx/ValidatePostalCode',
dataFilter: function(data) { return $.parseJSON(data).d; }
};
return r;
}
来源:https://stackoverflow.com/questions/4759594/jquery-validatorremote-with-asp-net-webforms