Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
like image 736
K.Z Avatar asked Feb 07 '26 06:02

K.Z


1 Answers

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;
    }
like image 118
K.Z Avatar answered Feb 08 '26 21:02

K.Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!