jQuery Validator#remote with ASP.NET WebForms

孤街醉人 提交于 2020-01-14 04:33:07

问题


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

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