2012-10-08 46 views
1

我有GridView,文本框,一个HTML按钮。它所做的是文本框包含一个值,点击html按钮后将保存在数据库中。如何在jquery ajax调用后重新加载asp.net GridView?

Here is the code for the page: 

<div> 
     <div id="Gridview-container"> 
      <asp:GridView ID="GridView1" runat="server"> 
      </asp:GridView> 
     </div> 
     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
     <input type="button" id="btn" value="insert" /> 

    </div> 
    </form> 

    <script type="text/javascript"> 

     $("#btn").click(function() { 
      var a = $("#TextBox1").val(); 

      $.ajax({ 
       url: 'WebService.asmx/insert', 
       data: "{ 'name': '" + a + "' }", 
       dataType: "json", 
       contentType: "application/json; charset=utf-8", 
       type: "POST", 
       success: function() { 

        //alert('insert was performed.'); 
        $("#Gridview-container").empty(); 


       } 
      }); 

     }); 


    </script> 

下面是代码后面的那一页:

public partial class GridViewCourses : System.Web.UI.Page 
{ 
    Database db = new Database(); 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     GridView1.DataSource = db.LoadCourses(); 
     GridView1.DataBind(); 
    } 
} 

下面是Web服务的代码:我想要的东西

public class WebService : System.Web.Services.WebService { 

    public WebService() { 

     //Uncomment the following line if using designed components 
     //InitializeComponent(); 

    } 

    [WebMethod] 
    public string HelloWorld() { 

     return "Hello World"; 
    } 

    [WebMethod] 
    public void insert(string name) 
    { 
     Database db = new Database(); 
     db.Add(name); 
    } 



} 

有作为GridView.DataBind同样的效果(),这样当我执行删除和更新时,GridView将根据数据库中的记录重新加载。

先生/女士,你的回答会有很大的帮助。谢谢++

回答

2

您可以使用UpdatePanel并将GridView放入其中。然后,为了从javascript提高后期效果,您将不得不使用__doPostBack并定位您的UpdatePanel。

这里的一些信息,应该帮助您实现这一点:http://encosia.com/easily-refresh-an-updatepanel-using-javascript/

+0

感谢您的回复,我只是想知道,如果它也有可能没有更新面板做:d –

+0

是的,但你将不得不做一个完整的回发(我推测你不想这样做)。 – martinwnet

0

你写在单独的方法GridView控件绑定代码。这样

public void dataBind() 

{

GridView1.DataSource = db.LoadCourses(); 
GridView1.DataBind(); 

}

[WebMethod] 
public void insert(string name) 
{ 
    Database db = new Database(); 
    db.Add(name); 
    //after successful insertion call dataBind 

    dataBind() //this method will update the grdivew with new data 

} 

,如果你想在定义代码隐藏文件将WebMethod为PageMethod的。

希望这有助于..

+1

插入方法位于Web服务中(除非我错过了某些内容),这将无法工作。 – martinwnet

+0

是的,这是行不通的,因为我无法访问webservice中的gridview,所以调用类似bind(GridView1)的东西;无法完成。 –

1

你必须把你的GridView更新面板&内莫名其妙地从客户方刷新。如果你想要做的一切客户方可以推倒重来&使用像JTable中&创建你自己的网格,但我不会建议

  1. 你可以这样做既可以使用__doPostback的Javascript
  2. 还是一个隐藏按钮田间地头您的网页上&呼吁关闭按钮客户方像

的document.getElementById( 'yourButton')的click事件点击()。

0

我意识到它有点旧的论坛。但是,我在按钮上使用UseSubmitBehavior = false。当然,使按钮成为一个asp:Button。并且,声明Onclick和OnClientClcik事件。这样,它会首先发起onclientclick事件,然后触发onclick事件。

斯里兰卡

0

添加下面的一行到你的jQuery的末尾:

$("#YourGridView").load(location.href + " #YourGridView"); 
相关问题