我的應用程序中有一個非常大的表單,其中有很多不同的輸入和我的模型中的很多列表。所以我會嘗試添加/刪除列表而不將完整的模型發送到服務器。將動態創建的元素綁定到視圖中的複雜mvc模型
我嘗試了幾種方法,但我沒有找到一個乾淨的方法。你可以想象我的模型是這樣的:
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
方法我在列表中的下一個元素的ID添加ViewBag.ListId
。
我已經改變了我的答案與你需要得到驗證不引人注目的變化在ajax回調後使用新的字段。 –
是的,看。但是您需要從您要提交的表單中刪除所有驗證。這將工作:var table ='$('#SomethingForm')。removeData(「validator」)。removeData(「unobtrusiveValidation」); $ .validator.unobtrusive.parse(table);'非常感謝 –