65.9K
CodeProject is changing. Read more.
Home

Call Cross Domain WebService(asmx) from Jquery with Jqgrid

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Apr 14, 2014

CPOL
viewsIcon

19366

How to call cross domain Webserver(asmx) service from jquery and bind the Json result with Jqgrid

Introduction

Today I am going to demonstrate how to call cross domain Webserver(asmx) service from jquery and bind the Json result with Jqgrid.

Please download Jqgrid library from here: JQueryFiles

Using the Code

As we know, within the same domain we can call webservice easily. But we cannot easily call the webservice that is hosted on a different domain. For this, we have to use some trick. Below is the example for the same.

Take an example of a webservice that return three columns named "ProductID", "ProductName", "Price" in Json format. Below is the sample code for the same.

        [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
        public void GetProductList()
        {
            string result = string.Empty;
            var products = new List<Product>();
            //DataSet ds = new DataSet();
            try
            {
                for (int i = 0; i < 50; i++)
                {
                    var product = new Product();
                    product.ProductID = i;
                    product.ProductName = "Product " + i;
                    product.Price = i * 20;
 
                    products.Add(product);
                }
 
                result = new JavaScriptSerializer().Serialize(products);
 
                // Prepare
                string callback = HttpContext.Current.Request.Params["callback"];
                string json = "{d: " + result + "}";
                string response = string.IsNullOrEmpty(callback) ? json : string.Format("{0}({1});", callback, json);
 
                // Response
                HttpContext.Current.Response.ContentType = "application/json";
                HttpContext.Current.Response.Write(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }  

Put the following tag in your webservice web.config under <system.web> tag:

    <webServices>
      <protocols>
        <add name="HttpGet"/>
      </protocols>
    </webServices> 

Assume webservice is hosted on http://localhost:1235/ProductWebService.asmx.

Now put the below listed jquery and CSS files on your master page inside the head tag.

    <script src="/JQueryFiles/js/jquery-1.7.2.min.js" 
    type="text/javascript"></script>
    <link href="/JQueryFiles/css/ui.jqgrid.css" 
    rel="stylesheet" type="text/css" />
    <link rel="stylesheet" type="text/css" 
    href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/redmond/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" 
    href="~/JQueryFiles/jquery.jqGrid-3.7.2/css/ui.jqgrid.css" />
    <script src="/JQueryFiles/js/grid.locale-en.js" 
    type="text/javascript"></script>
    <script src="/JQueryFiles/js/jquery.jqGrid.min.js" 
    type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.jgrid.no_legacy_api = true;
            $.jgrid.useJSON = true;
        });
    </script> 

Now the following code is placed on your web page:

 <script type="text/javascript">
        var lastsel = 0;
        var gridData;
        var selectedRowIndex = 0;
        $(function () {
            BindGrid();
        });
 
        function BindGrid() {
 
            // jQuery functions go here...
            $("#jqGrid").jqGrid({
                url: 'http://localhost:1235/ProductWebService.asmx/GetProductList?callback=?',
                datatype: "jsonp",
                mtype: 'GET',
                ajaxGridOptions: { contentType: 'application/json; charset=utf-8' }, //Specified content type of output.
                serializeGridData: function (postData) {
 
                    try {
                        return JSON.stringify(postData);
                    } catch (e) {
 
                    }
                },
                jsonReader: { repeatitems: false, root: "d" },
                colNames: ['ID'
                                            , 'Name'
                                            , 'Price'
 
                                        ],
 
                colModel: [{ name: 'ProductID', index: 'ProductID', sorttype: "int" }
                                            , { name: 'ProductName', index: 'ProductName', sorttype: "string" }
                                            , { name: 'Price', index: 'Price', sorttype: 'decimal;' }
 
 
                                        ],
                rowNum: 20,
                rowList: [10, 20, 30],
                autowidth: true,
                pager: '#jqGridPager',
                sortname: 'id',
                viewrecords: true,
                sortorder: "desc",
                loadonce: true,
                height: 230,
                caption: "Product List",
                ignoreCase: true,
 
                gridComplete: function () {
                    gridData = $("#jqGrid").jqGrid('getRowData');
                    if (selectedRowIndex > 0) {
                        jQuery("#jqGrid").setSelection(selectedRowIndex, true);
                    }
 
                    //Set default values in Key hidded field and CommandName hidden field.
                    document.getElementById('<%= hfRowKey.ClientID %>').value = "";
                    document.getElementById('<%= hfCommandName.ClientID %>').value = "";
                },
                onSelectRow: function (id) {
                    selectedRowIndex = id;
 
                }
 
            }).jqGrid('navGrid', '#jqGridPager', { edit: false, add: false, del: false, search: true })
                            .navButtonAdd('#jqGridPager',
                            { caption: "Edit", onClickButton: function (id) {
                                var RowKey = 0;
                                if (selectedRowIndex > 0) {
 
                                    RowKey = $('#jqGrid').getCell(selectedRowIndex, 'ID');
                                    if (RowKey > 0) {
                                        document.getElementById('<%= hfRowKey.ClientID %>').value = "" + RowKey;
                                        document.getElementById('<%= hfCommandName.ClientID %>').value = "edit";
 
                                    }
 
                                    $("#" + '<%= btnAddNew.ClientID %>').click();
                                }
                                else {
                                    alert("Please select row for editing.");
                                }
 
 
                            }, position: "last"
                            })
                            .navButtonAdd('#jqGridPager', { caption: "Delete", buttonimg: "../Images/delete-icon.png",
                                onClickButton: function (id) {
                                    var RowKey = 0;
                                    if (selectedRowIndex > 0) {
                                        var r = confirm("Are you sure, you want to delete this record : " + 
                                        $('#jqGrid').getCell(selectedRowIndex, 'Name') + " ?");
                                        if (r == true) {
                                            RowKey = $('#jqGrid').getCell(selectedRowIndex, 'ID');
                                            if (RowKey > 0) {
                                                document.getElementById('<%= hfRowKey.ClientID %>').value = "" + RowKey;
                                                document.getElementById('<%= hfCommandName.ClientID %>').value = "delete";
                                            }
                                            $("#" + '<%= btnAddNew.ClientID %>').click();
                                        }
                                    }
                                    else {
                                        alert("Please select row to delete.");
                                    }
 
                                }, position: "last"
                            });
        }
    </script>
<pre style="background-attachment: initial; background-clip: initial; background-color: white; background-image: initial; background-origin: initial; font-family: Consolas; font-size: 13px;"><pre style="background-attachment: initial; background-clip: initial; background-color: white; background-image: initial; background-origin: initial; color: black; font-family: Consolas; font-size: 13px;"><asp:HiddenField ID="hfRowKey" runat="server" Value="" />
    <asp:HiddenField ID="hfCommandName" runat="server" Value="" />
    <asp:Button ID="btnAddNew" runat="server" Text="Add New" OnClientClick="javascript:return false;"
        Style="display: none;" CommandArgument="testarg" />
    <table id="jqGrid" style="width: 100%;">
    </table>
    <div id="jqGridPager">
    </div> 

Result