Hi all,
Here's an example of databinding an ASP.NET Gridview with jQuery. The jQuery binding occurs when a dropdownlist keyup/selection occurs.
For the server side, I bind the gridview with all the products and dropdownlist with all subcategories. There's also a webmethod that handles
client side databinding.
Client Side Databinding using jQuery/javascript
javascript Code:
<script type="text/javascript"> $(document).ready(function () { $('#<%=ddlProductCategory.ClientID%>').bind("change keyup", function () { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "Default.aspx/GetProductsByCategory", data: '{data: ' + $('#<%=ddlProductCategory.ClientID%>').val() + '}', dataType: "json", success: function (response) { //clear rows below header $("#gvProducts tr:not(:first-child)").html(""); //add new table rows for (var i = 0; i < response.d.length; i++) { $('#<%=gvProducts.ClientID%>').append("<tr><td>" + response.d[i].ProductName + "</td><td>" + response.d[i].ProductNumber + "</td><td>" + response.d[i].ProductReorderPoint + "</td></tr>"); } }, error: function(result) { alert("Databinding unsuccessful!"); } }); }); }); </script>
WebMethod called by jQuery
csharp Code:
[WebMethod] public static IEnumerable<ProductInformation> GetProductsByCategory(string data) { products = new List<ProductInformation>(); dtResult = new DataTable(); try { String strConnString = ConfigurationManager.ConnectionStrings["AdventureWorks2012"].ConnectionString; String strQuery = "SELECT ProductNumber, [Name] as ProductName, ReorderPoint FROM [Production].[Product] where ProductSubcategoryID=" + data; SqlConnection con = new SqlConnection(strConnString); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = strQuery; cmd.Connection = con; SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd); try { con.Open(); dataAdapter.Fill(dtResult); if (dtResult.Rows.Count > 0) { foreach (DataRow row in dtResult.Rows) { products.Add(new ProductInformation() { ProductName = row["ProductNumber"].ToString(), ProductNumber = row["ProductName"].ToString(), ProductReorderPoint = row["ReorderPoint"].ToString() }); } } } catch (Exception ex) { throw ex; } finally { con.Close(); con.Dispose(); } } catch (Exception exception) { throw; } return products; }
Software used:
VS 2012, AdventureWorks 2012 database, SQL Server 2012, ASP.NET 4.5.
KGC





Reply With Quote