jQuery $Ajax Post data from webform to code behind method in ASP.NET

Toxic picture Toxic · Sep 22, 2015 · Viewed 12.2k times · Source

I am trying to pass data from webform to code behind method and get back value in webform, followed by print it. I have initially test following code to simply post request to method, get string and print in page and it worked, but got issue when trying to post data back to method

$(document).ready(function () {

$(".AddStaffToRoleLink").on("click", function () {

           var selectedStaffID = $(this).attr("id");

           alert("this is " + selectedStaffID);

           $.ajax({

               type: "POST",
               url: "AddUserInRole.aspx/AddRoleForSelectStaff",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               data: { selectedStaffID: selectedStaffID },
               success: function (response) {
                   $("#Content").text(response.d);
               },
               failure: function (response) {
                   alert(response.d);
               }
           });
       });

});

Code behind

   [WebMethod]
    public static string AddRoleForSelectStaff(string selectedStaffID)
    {
        return "This string is from Code behind  " + selectedStaffID;
    }

Answer

Toxic picture Toxic · Sep 22, 2015

here is way to post sigle data to webform code behind method...

  $(document).ready(function () {

 $(".AddStaffToRoleLink").on("click", function () {

           var selectedStaffID = $(this).attr("id");

           alert("this is " + selectedStaffID);

           $.ajax({
               url: 'AddUserInRole.aspx/AddRoleForSelectStaff',
               type: "POST",
               data: "{'GivenStaffID':'" + selectedStaffID +"'}",
               contentType: "application/json; charset=utf-8",
               dataType: "json",
               success: function (response) {
                   $("#Content").text(response.d);
               },
               failure: function (response) {
                   alert(response.d);
               }
           }).done(function (response) {
               alert("done "+response );
           });
       });
   });

Code Behind method

 [WebMethod]
    public static string AddRoleForSelectStaff(string GivenStaffID)
    {
        var staffID = Convert.ToInt32(GivenStaffID);

        return "This string is from Code behind  " + GivenStaffID;
    }