我是 asp.net mvc 的新手,并且在将新项目添加到表显示的项目列表中后,正在努力找到刷新表的正确方法。
"添加新项"控件与列表位于同一页上。因此,当用户单击"添加"时,我想将其添加到数据库中并在下表中显示刷新的列表。当我让控制器将其添加到数据库中时,我无法刷新列表。您能否告诉我在这种情况下刷新表格的方法?
这是我的观点——
<table>
<tr>
<td>
<input id="txtAddName" type="text" />
</td>
<td>
<button id="btnAdd" onclick="Add(); return false;">Add</button>
</td>
</tr>
</table>
<table width="100%">
<tr>
<th>Name</th>
</tr>
@foreach (var m in Model)
{
<tr>
<td>
<input id="txtName-@m.Id.ToString()" type="text" value="@m.Name.ToString()" />
</td>
</tr>
}
</table>
function Add() {
var _Name = $("#txtAddName").val();
var url = '@Url.Action("Create", "Item")';
$.post(
url,
{
Name: _Name
},
function (data) {
});
}
控制器-
[AcceptVerbs("POST")]
public ActionResult Create(string name)
{
// Logic to add item goes here
// What do I return here? I would want my table to now display the refreshed (including the new item)
}
[HttpGet]
public ActionResult List()
{
// List is the action method that returns the initial list, both these are in the same controller
return View(data);
}
您必须像下面这样更改控制器:
[AcceptVerbs("POST")]
public ActionResult Create(string name)
{
// Logic to add item goes here
// What do I return here? I would want my table to now display the refreshed (including the new item)
return RedirectToAction("List");//redirect to List Action Method
}
[HttpGet]
public ActionResult List()
{
// List is the action method that returns the initial list, both these are in the same controller
return View(data);
}
注意:在上述列表操作方法中,您必须从数据库中获取最新数据并发送回View。
最新更新 :
在这里,我将介绍如何显示带有来自控制器的项目列表的表。
尝试在应用程序中使用这种视图来显示内容。
<div class="boxedForm">
<table id="productDetails">
<tr>
<th>
Product Name
</th>
<th style="text-align: center;">
UPC Code
</th>
</tr>
@ foreach (var p in Model.ProductList)
{
<tr class="row">
<td>
@p.ProductName
</td>
<td>
@p.UpcCode
</td>
</tr>
}
</table>
</div>
我的视图模型就像
public class ProductViewModel
{
public virtual ICollection<Product> ProductList { get; set; }
}
我的模型就像
public class Product
{
public Product() { Id = Guid.NewGuid(); Created = DateTime.Now; }
public string ProductName { get; set; }
public string UpcCode { get; set; }
}
更新 2 :
尝试使用如下所示的发布方法:
function Add() {
var _Name = $("#txtAddName").val();
var url = '@Url.Action("Create", "Item")';
$.post(
url,
{
Name: _Name
},
function (data) {
var url = Sys.Url.route('YourRouteName', { action: "List", controller: "YourControllerName"});
window.location = url;
});
}