views:

124

answers:

2

I have searched everywhere, and I can't seem to find a solid example.

Is anyone doing this? Can anyone provide and example of calling a remote validation using the JQuery validation plugin through a WebMethod in an aspx page (Web Forms)?

+1  A: 

Just as I posted this I found a way that works, but I really don't like it. It is very cumbersome and requires constructing your own Json, which doesn't seem like a good solution.

var validated = $("#aspnetForm").validate(
    {
        rules:
        {
            customersToReassign:
            {
                required: true
            },
            customerToAssignTo:
            {
                required: true,
                remote: 
                {
                    url: window.location + "/IsValidCustomer",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: "{'customerToAssignTo':'" + $("#customerToAssignTo").val() + "'}"
                }
            }
        },
John Sonmez
+2  A: 

I think the reason that code gives you a bad taste is because writing json as strings is pretty smelly. One slight improvement would be to create a real JSON object and then use the JSON.stringify(...) function.

Create a variable with your json object, this gives you syntax checking at design time and run time

var customerInput = {"customerToAssignTo":$("#customerToAssignTo").val()};
var serializedCustomerInput = JSON.stringify(customerInput );

then you could replace the line

data: "{'customerToAssignTo':'" + $("#customerToAssignTo").val() + "'}"

with

data: serializedCustomerInput

you would need to include http://www.json.org/json2.js

more info:

http://www.json.org/js.html

http://msdn.microsoft.com/en-us/library/cc836459(VS.85).aspx - this is in the context of windows scripting but gives a good description of the function

Tion