使用Html.BeginCollectionItem帮助程序传递集合的部分视图 [英] A Partial View passing a collection using the Html.BeginCollectionItem helper
问题描述
我做了一个小项目来理解Stephen Muecke的答案:将多次调用的同一局部视图提交给控制器?
I made a small project to understand the answer from Stephen Muecke here: Submit same Partial View called multiple times data to controller?
几乎一切正常。 javascript在Partial View中添加了新的字段,我可以通过控制器方法为局部视图插入的temp值来判断它们是否与模型绑定。
Almost everything works. The javascript adds new fields from the Partial View, and I can tell they're bound to the model by the "temp" values inserted by the controller method for the partial view.
但是,当我提交新字段时,AddRecord()方法抛出一个异常,表明模型没有被传入(对象引用未设置为对象的实例)。
However, when I submit the new fields the AddRecord() method throws an exception showing that the model isn't getting passed in ("Object reference not set to an instance of an object").
此外,当我查看页面源时,BeginCollectionItem帮助器正在主视图中的表周围插入一个隐藏标记,该标记显示预先存在的记录,但不包括新的字段周围javascript添加。
Also, when I view the page source, the BeginCollectionItem helper is inserting a hidden tag as it should around the table in the main view that displays pre-existing records, but not around the new fields that the javascript adds.
我做错了什么?我很擅长这一点,谢谢你的耐心等待!
What am I doing wrong? I'm pretty new at this so thanks for your patience!
我的主要观点:
@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);
}
推荐答案
首先创建一个视图用于表示您要编辑的内容的模型。我假设 cashAmount
是货币值,因此应该是小数(根据需要添加其他验证和显示属性)
First start by creating a view model to represent what you want to edit. I'm assuming cashAmount
is a monetary value, so therefore should be a decimal (add other validation and display attributes as required)
public class CashRecipientVM
{
public int? ID { get; set; }
public decimal Amount { get; set; }
[Required(ErrorMessage = "Please enter the name of the recipient")]
public string Recipient { get; set; }
}
然后创建局部视图(比方说) _Recipient .cshtml
Then create a partial view (say) _Recipient.cshtml
@model CashRecipientVM
<div class="recipient">
@using (Html.BeginCollectionItem("recipients"))
{
@Html.HiddenFor(m => m.ID, new { @class="id" })
@Html.LabelFor(m => m.Recipient)
@Html.TextBoxFor(m => m.Recipient)
@Html.ValidationMesssageFor(m => m.Recipient)
@Html.LabelFor(m => m.Amount)
@Html.TextBoxFor(m => m.Amount)
@Html.ValidationMesssageFor(m => m.Amount)
<button type="button" class="delete">Delete</button>
}
</div>
以及返回该部分的方法
public PartialViewResult Recipient()
{
return PartialView("_Recipient", new CashRecipientVM());
}
那么你的主要GET方法将是
Then your main GET method will be
public ActionResult Create()
{
List<CashRecipientVM> model = new List<CashRecipientVM>();
.... // add any existing objects that your editing
return View(model);
}
,其视图将是
@model IEnumerable<CashRecipientVM>
@using (Html.BeginForm())
{
<div id="recipients">
foreach(var recipient in Model)
{
@Html.Partial("_Recipient", recipient)
}
</div>
<button id="add" type="button">Add</button>
<input type="submit" value="Save" />
}
并将包含一个脚本,用于为新的<$ c $添加html c> CashRecipientVM
and will include a script to add the html for a new CashRecipientVM
var url = '@Url.Action("Recipient")';
var form = $('form');
var recipients = $('#recipients');
$('#add').click(function() {
$.get(url, function(response) {
recipients.append(response);
// Reparse the validator for client side validation
form.data('validator', null);
$.validator.unobtrusive.parse(form);
});
});
以及删除商品的脚本
$('.delete').click(function() {
var container = $(this).closest('.recipient');
var id = container.find('.id').val();
if (id) {
// make ajax post to delete item
$.post(yourDeleteUrl, { id: id }, function(result) {
container.remove();
}.fail(function (result) {
// Oops, something went wrong (display error message?)
}
} else {
// It never existed, so just remove the container
container.remove();
}
});
表格将发回
public ActionResult Create(IEnumerable<CashRecipientVM> recipients)
这篇关于使用Html.BeginCollectionItem帮助程序传递集合的部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!