【发布时间】:2015-04-15 11:14:45
【问题描述】:
我是 asp.net MVC 的新手。我的项目中有一个动态表。在表中添加动态行是通过以下链接实现的
Adding and deleting rows in dynamic table in Asp.net mvc razor view
我需要编辑和更新动态表。 我试过下面的代码
我的示例模型
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
public class GiftViewModel
{
public string Age { get; set; }
public DateTime TheDate { get; set; }
public IEnumerable<Gift> Gifts { get; set; }
}
我的示例控制器
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(GiftViewModel model)
{
// do work here
return RedirectToAction("Index");
}
public ViewResult AddNew()
{
return View("_TimeSheetView");
}
}
我的示例局部视图
@model HelloWorldMvcApp.Gift
@using (Html.BeginCollectionItem("giftList"))
{
<div>
<span class="drop_medium">
@Html.TextBoxFor(m => m.Name)
</span>
<span class = "drop_medium">
@Html.TextBoxFor(m => m.Price)
</span>
</div>
}
我的示例主视图
@model HelloWorldMvcApp.GiftViewModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.Age)
@foreach (var data in Model.Gifts)
{
{ Html.RenderPartial("_TimeSheetView", data); }
}
@Html.ActionLink("Add another", "AddNew", null, new { id="addItem" })
<input type="submit" value="Save"/>
}
<script type="text/javascript">
$("#addItem").click(function () {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#dynamic").append(html); }
});
return false;
});
</script>
当我单击“添加另一个”按钮时,表格中会添加一行。编辑表中的值后,当我单击提交按钮时,控制器中什么也没有收到。 IEnumerable Gifts 变量为空。如何将表值带到控制器。请帮我解决这个问题。提前致谢
【问题讨论】:
-
你的模型属性被命名为
Gifts,所以它需要是Html.BeginCollectionItem("Gifts"))(不是"giftlist")。而且您还没有显示添加新项目的脚本。 -
@StephenMuecke 添加新行没问题。我会按照你说的修改代码并通知你
-
@StephenMuecke 正如你所说,我将“礼物清单”更改为“礼物”,但没有奏效。我收到礼物为空
-
检查你生成的html。您应该看到
<input name="Gifts[##].Name" ...> <input type="hidden" name="Gifts.Index" value="##" >其中##是一个Guid -
@StephenMuecke 感谢您的帮助,现在它工作正常。错误是我在控制器中使用了同名的“礼物”来接收视图中的值。更改名称后它起作用了。
标签: c# asp.net-mvc-4 razor