kavitha vemula kavitha vemula - 5 months ago 30
jQuery Question

passing webmethod parameter to another web method

how can we call one web method in another web method using ajax from the first web method i need to call another web method and pass the parameters from the first to second method

<script type = "text/javascript">
function GetCityNameArray() {
var cities = ['Mumbai', 'Delhi', 'Chennai'];
PageMethods.GetCityNameArray(cities, OnSuccessGetCityNameArray);
}
function OnSuccessGetCityNameArray(response) {
for (var i in response) {
alert(response[i]);
}
}
</script>

<form id="form1" runat="server">

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true">
</asp:ScriptManager>

<div>

<input type = "button" onclick = "GetCityNameArray()" value = "Get City Name Array" />

</div>
</form>

protected void Page_Load(object sender, EventArgs e)
{

}

[System.Web.Services.WebMethod]
public static string[] GetCityNameArray(string[] cities)
{
return cities;
}

Answer

There can be a few corrections first of all you need document.ready event or another helper function (i changed to a helper function due to asp.net's clientid thing) and then you have to stop button posting back your page.

script type="text/javascript">
    var onSubmitClick = function() {
            var button = this;
            var obj = {};
            obj.name = $.trim($("[id*=txtName]").val());
            obj.age = $.trim($("[id*=txtAge]").val());
            $.ajax({
                type: "POST",
                url: "CS.aspx/SendParameters",
                data: JSON.stringify(obj),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {
                    alert(r.d);
                }
            });
            return false;
    };
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>

<table border="0" cellpadding="0" cellspacing="0">
<tr>
    <td>
        Name:
    </td>
    <td>
        <asp:TextBox ID="txtName" runat="server" Text = "" />
    </td>
</tr>
<tr>
    <td>
        Age:
    </td>
    <td>
        <asp:TextBox ID="txtAge" runat="server" Text = ""/>
    </td>
</tr>
<tr>
    <td>
        <asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClientClick="return onSubmitClick();" UseSubmitBehaviour="false" />
    </td>
</tr>
</table>

protected void Page_Load(object sender, EventArgs e)
        {

        }

        [System.Web.Services.WebMethod]
        public static string SendParameters(string name, int age)
        {
            return string.Format("Name: {0}{2}Age: {1}", name, age, Environment.NewLine);
        }