我做了一个小项目来理解 Stephen Muecke 的答案:Submit same Partial View called multiple times data to controller?
几乎一切正常。javascript 从局部视图中添加新字段,我可以通过控制器方法为局部视图插入的“临时”值来判断它们已绑定到模型。
但是,当我提交新字段时,AddRecord() 方法会引发异常,表明模型没有被传入(“对象引用未设置为对象的实例”)。
此外,当我查看页面源代码时,BeginCollectionItem 助手正在插入一个隐藏标记,因为它应该在显示预先存在的记录的主视图中的表周围,而不是在 javascript 添加的新字段周围。
我究竟做错了什么?我对此很陌生,所以感谢您的耐心等待!
我的主要观点:
@model IEnumerable<DynamicForm.Models.CashRecipient>
@using (Html.BeginForm("AddDetail", "CashRecipients", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div id="CSQGroup">
</div>
}
<div>
<input type="button" value="Add Field" id="addField" onclick="addFieldss()" />
</div>
<script>
function addFieldss()
{
//alert("ajax call");
$.ajax({
url: '@Url.Content("~/CashRecipients/RecipientForm")',
type: 'GET',
success:function(result) {
//alert("Success");
var newDiv = document.createElement("div");
var newContent = document.createTextNode("Hi there and greetings!");
newDiv.appendChild(newContent);
newDiv.innerHTML = result;
var currentDiv = document.getElementById("div1");
document.getElementById("CSQGroup").appendChild(newDiv);
},
error: function(result) {
alert("Failure");
}
});
}
</script>
我的部分观点:
@model DynamicForm.Models.CashRecipient
@using HtmlHelpers.BeginCollectionItem
@using (Html.BeginCollectionItem("recipients"))
{
<div class="editor-field">
@Html.LabelFor(model => model.Id)
@Html.LabelFor(model => model.cashAmount)
@Html.TextBoxFor(model => model.cashAmount)
@Html.LabelFor(model => model.recipientName)
@Html.TextBoxFor(model => model.recipientName)
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}
我的模型:
public class CashRecipient
{
public int Id { get; set; }
public string cashAmount { get; set; }
public string recipientName { get; set; }
}
在我的控制器中:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDetail([Bind(Include = "Id,cashAmount,recpientName")] IEnumerable<CashRecipient> cashRecipient)
{
if (ModelState.IsValid)
{
foreach (CashRecipient p in cashRecipient) {
db.CashRecipients.Add(p);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(cashRecipient);
}
public ActionResult RecipientForm()
{
var data = new CashRecipient();
data.cashAmount = "temp";
data.recipientName = "temp";
return PartialView(data);
}