How to call a method on a server side from JSON. Below is the code I am using
SERVER SIDE:
[WebMethod]
private void GetCustomer( string NoOfRecords)
{
string connString = "Data Source=Something;Initial Catalog=AdventureWorks;Trusted_Connection=True;";
SqlConnection sCon = new SqlConnection(connString);
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Sales.Customer WHERE CustomerID < '" + NoOfRecords+ "' ", sCon);
DataSet ds = new DataSet();
da.Fill(ds);
GvDetails.DataSource = ds.Tables[0];
GvDetails.DataBind();
}
On Client Side:
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
<asp:Button ID="btnShow" runat="server" Text="Sow Records without PostBack" />
<asp:GridView ID="GvDetails" runat="server">
</asp:GridView>
</div>
<script language="javascript" type="text/javascript">
var txtID = document.getElementById('txtValue');
$.ajax({
type: "POST",
url: "Default.aspx/GetCustomer",
data: "{Seconds:'" + txtID +"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response);
}
});
</script>
Now I want that on button click, I would call the function at the client side [JSON], which pass the textbox value to the function.
Please help
It looks like you are wanting to re-bind the grid and have it update on the page. The easiest thing to do in that case, is put your button and the grid in an update panel. Give the button a server side click event. Because it is in the update panel, it will handle the ajax call for you using ajax, and the contents of the update panel will automatically update.
If you want to do the ajax calls manuall, you won’t be able to just bind the grid like that, instead you GetCustomer method will need to return something which would get used by your client javascript. I find that rather than use $.ajax call (jquery), if you put the ScriptService tag on the method, you can make a javascript call PageMethods.GetCustomer(NoOfRecords). The javascript call syntax is exactly like the c# syntax you declared the method with, but in javascript you add “PageMethods.” in front.
Something like this:
Html: