Monthly Archives: August 2015

ASP.NET Webforms, WebMethod, JSON, and Jquery

Using JSON Serializers such as Newtonsoft’s JSON library is not needed in later versions of ASP.NET.

Instead, if you’re sending a JSON object via AJAX, the webforms framework will attempt to automatically deserialize the object into the type passed into the parameter and serialize the object when it is being returned to the page.

Example:

ASPX Page – Binding a button that submits a JSON Object

<script type="text/javascript">
   
    $(document).ready(function () {

        $('#<%=ButtonSubmit.ClientID%>').click(function () {
            var InputObj = {
                "InputObj": {
                    "IsAvailable": 0,
                    "Input": $('#<%=TextInput.ClientID%>').val()
                }
            }

            $.ajax({
                type: 'POST',
                url: '/Templates/UI/Views/MobileLocator.aspx/CheckZip',
                data: JSON.stringify(InputObj),
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                async: true,
                cache: false,
                success: function (obj) {
                    if (obj.d.IsAvailable === '1') {                       
                        $('#divyes').reveal();
                    }
                    else {
                        $('#divno').reveal();
                    }                    
                }

            });

            return false;
        });
    });
</script>

CodeBehind – Static WebMethod

        [WebMethod(BufferResponse=false)]
        public static FormInputObj CheckZip(FormInputObj InputObj)
        {            
                                                  
                if (InputObj != null && !string.IsNullOrEmpty(InputObj.Input))
                {
                    bool iIsAvailable = false;
                   
                    InputObj.IsAvailable = iIsAvailable ? "1" : "0";

                    return InputObj;
                }
            

            return new FormInputObj { IsAvailable = "0" };
        }

    [Serializable]
    public class FormInputObj
    {        
        public string Input { get; set; }        
        public string IsAvailable { get; set; }
    }

The only things to note are the following:

When serializing the object into JSON format using Jquery, make sure the parameter’s name is the parent object. Example:

var InputObj = {
                "InputObj": {
                    "IsAvailable": 0,
                    "Input": $('#<%=TextInput.ClientID%>').val()
                }
            }

The “InputObj” matches the parameter name in the codebehind. This is needed or else ASP.NET will return an error. You must also call

JSON.stringify(InputObj)

when creating the parameters for data key in the $.ajax method.

When reading the returned object in the Jquery success event, you must reference the ‘.d’ in the returned object before calling the property of the strongly typed object.

 if (obj.d.IsAvailable === '1')

Most Q&A topics on Stackoverflow regarding this are outdated. Ignore any articles circa 2013 or earlier regarding this topic.

Reference:

http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/