Search code examples
jquerypagemethodswebmethod

Read out result of a PageMethod into a jQuery-script


I am quite a jQuery novice and try to read out the result of a PageMethod into my jQuery script. I have a ScriptManager installed and the following WebMethod:

[WebMethod(EnableSession = true)]
    public static string CheckSystemDefault(string _id)
    {
        int id = Convert.ToInt16(_id);
        addressTypeRepository = new AddressTypeRepository();

        AddressType addressType = addressTypeRepository.GetById(id);

        if (addressType.IsSystemDefault == true)
            return "IsSystemDefault";
        else
            return "IsNotSystemDefault";
    }

I use this to check if an object has the property IsSystemDefault.

In the script, I hand over the id from the url and want to evaluate the result:

var id = $(document).getUrlParam("id");
var check = PageMethods.CheckSystemDefault(id);
if (check == "IsSystemDefault") {
...
}
if (check == "IsNotSystemDefault") {
...
}

But as a result, the variable "check" is undefined. What do I have to change?


Solution

  • The syntax in my jQuery-script was not correct.

    It has to be the following:

    <script type="text/javascript">
    
        jQuery(document).ready(function() {
    
            var id = $(document).getUrlParam("id"); 
    
            PageMethods.CheckSystemDefault(id, function(result) {
                if (result == "IsSystemDefault")
                    // do something
                else
                    // do something
            });
    
        });    
    
    </script>