2016-07-28 61 views
4

我想使用ajax更新MVC中的表格。我已經使用ajax在數據庫中插入數據。我只是想在插入新行後更新表格。在ASP.NET MVC中使用AJAX刷新表格

PS。我試過搜索,但沒有幫助我,我仍然困惑。

Here is my code: 

Main page View: 

<div id="theTable"> 
    @Html.Partial("_IPTable") 
</div> 
    <script src="~/Scripts/jquery-1.10.2.min.js"></script> 
    <script src="~/Scripts/Admin.js"></script>"` 

Partial page View: 

<table id="table">` 
    <tr> 
     <th>ID</th> 
     <th>Line</th> 
     <th>Supplier</th> 
    </tr> 

    @foreach (var item in ViewBag.IPTable)` 
    { 
     <tr> 
      <td> 
       @item.ID 
      </td> 
      <td> 
       @item.Line 
      </td> 
      <td> 
       @item.Supplier 
      </td> 
     </tr> 

    } 
</table>enter code here 

Controller view: 

public ActionResult Admin() 
     { 
      // get data from database 
      return View(); 
     } 
public ActionResult _IPTable() 
     { 

      return PartialView(); 
     } 

用於插入新記錄的Ajax代碼:

<script> 
$(document).ready(function() { 
//function will be called on button click having id btnsave 
$("#btnSave").click(function() { 
    $.ajax(
    { 
     type: "POST", //HTTP POST Method 
     url: "AdminInsert", // Controller/View 
     data: { //Passing data 
      //Reading text box values using Jquery 
      Line: $("#txtLine").val(), 
      Supplier: $("#txtSupplier").val() 
     } 
    }); 
}); 

}); </script> 
+0

你的代碼在哪裏通過ajax插入一個新行? – Shyju

+0

我的意思是客戶端代碼。 – Shyju

+0

我把它貼在下面。 –

回答

4

您可以創建返回需要渲染你的表中的HTML標記的操作方法。讓我們創建一個視圖模型,使用它我們將傳遞表數據。

public class ItemVm 
{ 
    public string ItemId {set;get;} 
    public string Line {set;get;} 
    public string Supplier {set;get;} 
} 

現在在您的操作方法中,從表中獲取數據,加載到視圖模型類的列表併發送到視圖。因爲我不確定你的表結構/數據訪問機制。我將要硬編碼的項目。你可以用真實數據替換它。

public ActionResult TableData() 
{ 
    var items = new List<ItemVm>{ 
     new ItemVm { ItemId="A1", Line="L1", Supplier="S1" }, 
     new ItemVm { ItemId="A2", Line="L2", Supplier="S2" }  
    }; 
    return PartialView("TableData",items); 
} 

現在確保你的部分看法是強類型的,以我們的視圖模型

@model List<ItemVm> 
<table> 
@foreach(var item in Model) 
{ 
    <tr><td>@item.ItemId</td><td>@item.Line</td></td>@item.Supplier</td></tr> 
} 
</table> 

集合現在,所有你需要做的是,把這種操作方法,並與響應更新DOM回來了。您可以在插入新記錄的ajax調用的success事件處理程序中執行此操作。您可以使用jQuery load方法來更新DOM中的相關元素。

$(document).ready(function() { 
    $("#btnSave").click(function() { 

    $.ajax(
    { 
     type: "POST", //HTTP POST Method 
     url: "AdminInsert", // Controller/View 
     data: { //Passing data 
      //Reading text box values using Jquery 
      Line: $("#txtLine").val(), 
      Supplier: $("#txtSupplier").val() 
     } 
    }).success(function() { 
      $("#theTable").load("/YourControllerName/TableData"); 
     }); 
}); 

現在爲初始視圖,您可以使用我們的新的局部視圖。但是因爲它期望的列表是ItemVm,所以您需要顯式傳遞它,而不是通過ViewBag傳遞它。

+0

真棒! Voila Daniel請在使用$ .ajax時忽略ViewBag的使用。 您可以改爲使用@model。 –

+0

謝謝! PS它與TableData一起作爲局部視圖使用。 –