提问人:Sam7 提问时间:6/4/2013 更新时间:6/4/2013 访问量:582
jQuery 不显眼的 Ajax 表单在“每表行”场景中不起作用
jQuery unobtrusive Ajax Form not working in 'per-table-row' scenario
问:
我正在尝试有一个可编辑的表格,其中每一行都是一个可以单独提交的视图,以便获得模型验证等的所有好处。
这是我得到的: 型号:
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;
}
}
我测试了整个事情作为一个有效的列表(表 -> ul、tr -> li、td -> div),没问题! 但作为表格,它仅适用于第一次提交。一旦我再次提交同一行,就什么也没发生。我调试了它,问题似乎是,对于通过ajax出现的表单,没有抛出表单提交事件。 我很有信心这与asp mvc无关。 我想说,将表单直接放入 tr 中一定是一个问题。
以前有人遇到过这个问题吗? 您知道任何解决方法吗?
谢谢!
答:
0赞
Darin Dimitrov
6/4/2013
#1
我想说,将表单直接放入 tr 中一定是一个问题
是的,就是这样。您需要一个嵌套表
:
@model Mvc4TestApp.Models.PersonModel
<td colspan="3">
@using (Ajax.BeginForm("Edit", new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = string.Format("Person-{0}", Model.Id) }))
{
<table>
<tr>
<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>
</tr>
</table>
}
</td>
评论
0赞
Sam7
6/4/2013
谢谢,但这将使表格的使用无效,因为目的是对齐所有列。
评论