通过ajax插入数据后重新绑定Gridview

时间:2015-05-26 07:39:48

标签: c# asp.net gridview

我在 .aspx 中有一个简单的HTML页面,我从 .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();
    }
}

我想要的是在webmethod的ajax调用(在产品表中插入新数据)之后刷新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);
                    }
                });

2 个答案:

答案 0 :(得分:0)

GridviewBind()条件下再次调用绑定函数if以成功插入。像这样:

if (rowsAffected == 1)
{
   msg = "Poduct Saved Successfully";
   GridviewBind(
}

希望这有帮助。

答案 1 :(得分:0)

在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>