通过ajax插入数据后重新绑定Gridview
本文关键字:绑定 Gridview 新绑定 ajax 插入 数据 通过 | 更新日期: 2023-09-27 17:50:47
我在中有一个简单的HTML页面。aspx和我从.cs文件调用静态web方法。
现在我的HTML .aspx页面有一个Gridview,它在页面加载时加载。
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();
}
}
我想要的是在ajax调用webmethod(这是在产品表中插入新数据)后刷新gridview。
[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调用:
$.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);
}
});
在if
条件下再次调用绑定函数GridviewBind()
以成功插入。像这样:
if (rowsAffected == 1)
{
msg = "Poduct Saved Successfully";
GridviewBind(
}
在GridView中使用UpdatePanel
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>