2012-10-08 44 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"); 
相關問題