Hi All ,
how to pass the textbox value in webmethod in codebehind through ajax call method.
sample method :
$(function () {
// var stDt = $("#txtStartDt").val();
$.ajax({
type: "POST",
url: "InteractiveDashboard.aspx/Web_GetTotalSaleslist",
data: "{'StartDate':'" + stDt + "','EndDate':'" + EndDt + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
//alert(response.d);
alert("Error..1");
},
error: function (response) {
alert("Error..2");
alert(response);
}
});
});


Amit MohantyRank #112 · 20K reputationPosted May 23, 2024, 4:11 AM EDT
Try like this:
$(function () { var stDt = $("#").val(); var endDt = $("#").val(); $.ajax({ type: "POST", url: "InteractiveDashboard.aspx/Web_GetTotalSaleslist", data: JSON.stringify({ StartDate: stDt, EndDate: endDt }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { alert("Success: " + response.d); }, failure: function (response) { alert("Error: " + response.d); }, error: function (response) { alert("Error: " + response.responseText); } }); });Abhishek ChadhaRank #402 · 6.2K reputationPosted May 23, 2024, 4:11 AM EDT
you can follow the below steps:
Create a Web Method in Code-Behind:
YourPage.aspx.csfor Web Forms or a controller for MVC), create a static method and decorate it with the[WebMethod]attribute.using System.Web.Services; public partial class YourPage : System.Web.UI.Page { [WebMethod] public static string YourWebMethod(string textboxValue) { // Your logic here return "Received value: " + textboxValue; } }Call the Web Method using AJAX:
Call Web Method function callWebMethod() { var textboxValue = document.getElementById("textbox").value; $.ajax({ type: "POST", url: "YourPage.aspx/YourWebMethod", // Replace with your page and method name data: JSON.stringify({ textboxValue: textboxValue }), contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { alert(response.d); // Display the response }, error: function(xhr, status, error) { console.log(error); // Log any errors } }); }Retrieve and Process the Value in the Web Method:
[WebMethod] public static string YourWebMethod(string textboxValue) { // Process the textbox value return "Received value: " + textboxValue; }This way, when the "Call Web Method" button is clicked, the textbox value will be sent to the web method through an AJAX call, and the response from the web method will be displayed in an alert box