Alica Corwin Alica Corwin - 3 months ago 19
Ajax Question

Getting value out of key value pairs of AJAX POST request in asp.net web method

Hello there you can see in the screen shot that i receive key value pairs through my ajax post request but i dont know that how should i decode them in my web method.

[System.Web.Services.WebMethod]
public static string Get_Data(string funcParam)
{
return "";
}


My key value pair

Answer

You can create an object in javascript and send it to the [WebMethod] using JSON.stringify().The object will automatically be de-serialized to a C# class in the code behind.

Code behind:

public partial class CallingWebMethodFromJS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [System.Web.Services.WebMethod]
    public static string Get_Data(Parameters parameters)
    {
        System.Diagnostics.Debugger.Break();
        return "";
    }
}

public class Parameters
{
    public string Value1 { get; set; }
    public string Value2 { get; set; }
    public string Value3 { get; set; }
}

.ASPX:

<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnOK").click(function () {
                var parameters =
                    {
                        "Value1": $("#value1").val(),
                        "Value2": $("#value2").val(),
                        "Value3": $("#value3").val(),
                    };

                $.ajax({
                    type: "POST",
                    url: "CallingWebMethodFromJS.aspx/Get_Data",
                    contentType: "application/json",
                    data: JSON.stringify({ parameters: parameters }),
                    success: function (data) {
                        alert('success');
                    },
                    error: function (errordata) {
                        alert('failure');
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <input type="text" id="value1" />
        <input type="text" id="value2" />
        <input type="text" id="value3" />
        <input type="button" value="OK" id="btnOK" />
    </form>
</body>
Comments