【发布时间】:2013-11-21 22:16:26
【问题描述】:
我的应用程序中有一个非常大的表单,在我的模型中有很多不同的输入和很多列表。所以我会尝试添加/删除列表而不将完整的模型发送到服务器。
我现在尝试了几种方法,但我找不到干净的方法。你可以把我的模型想象成这样:
public class EditSomething
{
public string name { get; set;}
public List<something> somethingList { get; set;}
// a lot other fields...
public EditSomething(EditSomethingFromDatabase editSomethingFromDatabase)
{
name = editSomethingFromDatabase.Name;
somethingList = new List<SomethingModel>();
foreach(var something in editSomethingFromDatabase.Something)
{
somethingList.Add(new SomethingModel(editSomethingFromDatabase.Something));
}
}
}
另一个模型看起来很相似,但没有列表。
在视图中我有一个模型表:
<h2>Something</h2>
<div id="SomethingDiv">
<table id="SomethingTable">
<thead>
<tr>
<th>@Html.Label("SomethingName")</th>
<th>@Html.Label("SomethingID")</th>
<th></th>
</tr>
</thead>
<tbody id="SomethingTableBody">
@Html.EditorFor(x => x.somethingList)
</tbody>
</table>
<p>
<input type="button" name="addSomething" value="Add Something" id="AddSomething">
</p>
</div>
addSomething 的 jquery 是:
$('#AddSomething').click(function () {
$.ajax({
url: '@Url.Action("AddSomething", "SomethingModels")',
data: { tableSize: $('#SomethingTable tr').length },
cache: false,
success: function (html) { $('#SomethingTable tr:last').after(html); }
});
控制器方法AddSomething是:
public ActionResult AddSomething (int tableSize)
{
SomethingModel something= new SomethingModel(null, (-2) * (tableSize + 1));
return PartialView(""~/Views/EditorTemplates/EditSomethingModel.cshtml"", something);
}
至少我在 EditorTemplates 中有一个编辑器模板,用于 editorfor 和 partialview。这有我想发送到服务器的重要信息:
@model SomethingModel
<tr>@TextBoxFor(m=>m.SomethingName)<td>
@TextBoxFor(m=>m.SomethingID)
所以现在的问题是,第一个视图的提交只将SomethingModel 发布到打开视图时已经存在的服务器,但AddMutation 方法中的新SomethingModel 不在帖子中。有人想解决这个问题吗?
编辑:更改了编辑器模板的路径,因此我只需要EditorFor 和PartialView 的一个视图。
Edit2:为了解决主要问题,我创建了如下视图并将其用作局部视图。现在数据已正确发送到服务器。只有客户端的验证仍然不起作用:
@model SomethingModel
<tr>@TextBoxFor(m=>m.SomethingName, new{Name="somethingList["+ViewBag.ListId+"].SomethingName")<span class="field-validation-valid" data-valmsg-for="somethingList[@ViewBag.ListId].SomethingName" data-valmsg-replace="true"></span><td>
<tr>@TextBoxFor(m=>m.SomethingID, new{Name="somethingList["+ViewBag.ListId+"].SomethingID")<span class="field-validation-valid" data-valmsg-for="somethingList[@ViewBag.ListId].SomethingID" data-valmsg-replace="true"></span><td>
</tr>
在AddSomething 方法中,我添加了ViewBag.ListId 以及列表中下一个元素的ID。
【问题讨论】:
-
我已经更改了我的答案,您需要进行更改以在 ajax 回调后获得不显眼的验证以使用您的新字段。
-
是的,见。但是您需要从要提交的表单中删除所有验证。这将起作用:var table =
$('#SomethingForm').removeData("validator").removeData("unobtrusiveValidation"); $.validator.unobtrusive.parse(table);非常感谢
标签: c# asp.net-mvc jquery asp.net-mvc-4