I have a simple HTML page in .aspx and I am calling a static web method from a .cs file.
Now my HTML .aspx page has a Gridview which is loading on page load.
protected void Page_Load(object sender, EventArgs e)
{
GridviewBind();
}
protected void GridviewBind()
{
using (SqlConnection con = new SqlConnection(connString))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select name,cost,description FROM products", con);
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
con.Close();
}
}
What I want is to refresh the gridview after the the ajax call for webmethod (which is inserting new data in product table).
[WebMethod]
public static string SaveProduct(string name, string desc, float cost)
{
string msg = string.Empty;
string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conn = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO products(name,description,cost) Values (@name,@description,@cost)";
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@description", desc);
cmd.Parameters.AddWithValue("@cost", cost);
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected == 1)
{
msg = "Poduct Saved Successfully";
}
else
{
msg = "Something Went Wrong...Please Try again later!!!";
}
}
}
catch (Exception e)
{
msg = "Something Went Wrong...Please Try again later!!!";
}
return msg;
}
Ajax call:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Products.aspx/SaveProduct",
data: "{'name':'" + name+ "','desc':'" + desc+ "','cost':'" + cost+ "'}",
dataType: "json",
success: function (data) {
alert(data);
clear();
},
error: function (data) {
alert(data);
}
});
Call your binding function GridviewBind()
again in your if
condition for successful insert. Like this :
if (rowsAffected == 1)
{
msg = "Poduct Saved Successfully";
GridviewBind(
}
Hope this helps.
Use UpdatePanel In GridView.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridviewBind();
}
}
<asp:UpdatePanel ID="updatepnl" runat="server">
<ContentTemplate>
---Put Your Grid View Code---
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSubmit" />
</Triggers>
</asp:UpdatePanel>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.