locked
How to pass a textbox value to web method which is located in asmx file using ajax? RRS feed

  • Question

  • User2015884762 posted

    Hi,

    I have a got a web page that has a javascript file with ajax call to a web method. The web method contains a call to database using stored procedure with parameter. If the sent parameter matches, the data will be returned in a array format. My question is how do I pass the textbox value to this ajax call and get the cmd.Parameters.Add in the execution of the stored procedure to retrieve the result. 

    These is my code : - I am actually passing the date in the textbox txtDate as the parameter.

    1. ASPX page : -
        <div>
                          <b>Date:</b> <asp:TextBox ID="txtDate" runat="server" ClientIDMode="Static"/>
                          <asp:Button ID="Button1" runat="server" Text="OK" OnClick="Button1_Click"/>
                      </div>
      JS file
    2. $.ajax({
          alert: ("It has started"),
      
          type: "post",
          url: "BarChart.asmx/CreateSubListTable",
          // data: "{ firstName: 'Aidy', lastName: 'F' }",
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (res, textStatus) {
              var data1 = JSON.parse(res.d);
              console.log(data1);
              createbarchart(data1);
              //pass the array of data1 into a function
              //drawdoughnutchat(data1);
              // console.log("Function called");
          },
          error: function (xhr, textStatus, error) {
              console.log(xhr.responseText);
              console.log(xhr.statusText);
              console.log(textStatus);
              console.log(error);
          }
      })
      3. SQL stored procedure in BarChart.asmx
    3.  public List<DenDate> AddListintoParentArr()
              {
                  List<DenDate> resultslistden = new List<DenonDate>();
                  using (SqlConnection con = new SqlConnection(constr))
                  {
                      using (SqlCommand cmd = new SqlCommand())
                      {
                          cmd.Connection = con;
                          cmd.CommandType = CommandType.StoredProcedure;
                          cmd.CommandText = "CheckforDateinTablesRough";
                          //cmd.Parameters.Add("@Value", SqlDbType.Date).Value = DateTime.ParseExact(LabelDate.Text, "dd/MM/yyyy", null);
                          con.Open();
      
                          SqlDataReader rdr = cmd.ExecuteReader();
                          while (rdr.Read())
                          {
                              DenDate results = new DenDate
                              {
                                  RunningJobTblName = rdr["TableName"].ToString(),
                                  TblNameShort = rdr["ShortForm"].ToString(),
                                  JobOrderName = rdr["JobOrderName"].ToString(),
                                  DeeProfileID = Convert.ToInt32(rdr["DeeProfileID"])
                                
                              };
                              resultslistden.Add(results);
                          }
                      }
                  }
      
      
      
      
                  return resultslistden;
                  //return jsonlist;
                  //return resultslistden.ToJSON2();
              }
      Please assist. Thank you in advance. Any guidance would be helpful.
    Thursday, May 20, 2021 5:23 AM

All replies

  • User-939850651 posted

    Hi callykalpana,

    callykalpana

    My question is how do I pass the textbox value to this ajax call and get the cmd.Parameters.Add in the execution of the stored procedure to retrieve the result. 

    You could use the selector to get the content of the html element and add it as a parameter to the Ajax method. And I see that you use <asp:Button>, I am not sure if there is any important operation in Button1_Click event, so I choose to keep it, in this case, you could use OnClientClick to trigger the Ajax call.

    A simple demo:

    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-3.5.1.min.js"></script>
        <script>
            function AjaxCall() {
                //alert("11");
                var txtDate = $('input[id*="txtDate"]').val();
                $.ajax({
                    //alert: ("It has started"),
                    type: "post",
                    url: "BarChart.asmx/CreateSubListTable",
                    data: '{ textDate: "' + txtDate + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (res, textStatus) {
                        //var data1 = JSON.parse(res.d);
                        alert(res.d);
                        //createbarchart(data1);
                        //pass the array of data1 into a function
                        //drawdoughnutchat(data1);
                        // console.log("Function called");
                    },
                    error: function (xhr, textStatus, error) {
                        console.log(xhr.responseText);
                        console.log(xhr.statusText);
                        console.log(textStatus);
                        console.log(error);
                    }
                })
            }
    
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <b>Date:</b>
                <asp:TextBox ID="txtDate" runat="server" ClientIDMode="Static" />
                <asp:Button ID="Button1" runat="server" Text="OK" OnClientClick="AjaxCall()" OnClick="Button1_Click" />
            </div>
        </form>
    </body>
    [System.Web.Script.Services.ScriptService]
        public class BarChart : System.Web.Services.WebService
        {
    
            [WebMethod]
            public string CreateSubListTable(string textDate)
            {
                return "Hello, the date you entered is: "+ textDate;
            }
        }

    Result:

    .

    Hope this can help.

    Best regards,

    Xudong Peng

    Friday, May 21, 2021 2:18 AM