我正在尝试创建一个可编辑的表格,其中每一行都是一个可以单独提交的视图,以便获得模型验证等的所有好处。
这是我所拥有的:
型号:
public class PeopleGroup
{
public string Name { get; set; }
public ICollection<PersonModel> People { get; set; }
}
public class PersonModel
{
[Required]
public uint Id { get; set; }
[Required]
[RegularExpression("[\\w\\s]{2,100}")]
[StringLength(100)]
public string FirstName { get; set; }
[Required]
[RegularExpression("[\\w\\s]{2,100}")]
[StringLength(100)]
public string LastName { get; set; }
}
列表显示:
@model Mvc4TestApp.Models.PeopleGroup
@{
ViewBag.Title = "People";
}
<h2>@Model.Name</h2>
<table>
@foreach (var item in Model.People)
{
<tr id="@string.Format("Person-{0}", item.Id)">
@Html.Partial("EditorSingle", item)
</tr>
}
</table>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
行(部分)视图:
@model Mvc4TestApp.Models.PersonModel
@using (Ajax.BeginForm("Edit", new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = string.Format("Person-{0}", Model.Id) }))
{
<td>@Html.EditorFor(x => x.FirstName)</td>
<td>@Html.EditorFor(x => x.LastName)</td>
<td>
<input type="submit" value="OK" />
@Html.HiddenFor(x => x.Id)
</td>
}
这里有一个控制器:
public class PeopleController : Controller
{
public ActionResult Index()
{
return View(new PeopleGroup()
{
Name = "Presidents",
People = GetPeople()
});
}
public ActionResult Edit(PersonModel model)
{
if (ModelState.IsValid)
{
var people = GetPeople();
var original = people.Where(x => x.Id == model.Id).SingleOrDefault();
if (original != null)
people.Remove(original);
people.Add(model);
}
return PartialView("EditorSingle", model);
}
public ICollection<PersonModel> GetPeople()
{
ICollection<PersonModel> collection = Session["people"] as ICollection<PersonModel>;
if (collection == null)
{
collection = new List<PersonModel>() {
new PersonModel() { Id = 0, FirstName = "George", LastName = "Washington"},
new PersonModel() { Id = 1, FirstName = "Abraham", LastName = "Lincoln"},
new PersonModel() { Id = 2, FirstName = "Thomas", LastName = "Jefferson"}
};
Session["people"] = collection;
}
return collection;
}
}
我将整个事情作为一个有效的列表(table -> ul,tr -> li,td -> div)进行了测试,没问题!但作为一个表格,它只适用于第一次提交。一旦我再次提交同一行,什么也没有发生。我调试了它,问题似乎是,没有为通过 ajax 传递的表单抛出表单提交事件。我非常有信心这与asp mvc无关。我会说将表单直接放入 tr 肯定是个问题。
以前有人遇到过这个问题吗?您知道任何解决方法吗?
谢谢!