使用Html传递一个集合的部分视图.BeginCollectionItem帮手
A Partial View passing a collection using the Html.BeginCollectionItem helper
我做了一个小项目来理解Stephen Muecke在这里的答案:提交相同的局部视图调用多次数据到控制器?
几乎所有的工作。javascript从局部视图中添加了新的字段,我可以看出它们是通过局部视图的控制器方法插入的"temp"值绑定到模型上的。
然而,当我提交新字段时,AddRecord()方法抛出一个异常,显示模型没有被传入("对象引用未设置为对象的实例")。
另外,当我查看页面源时,BeginCollectionItem helper正在插入一个隐藏的标签,因为它应该在显示预先存在的记录的主视图中围绕表,但不是围绕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>
My Partial View:
@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; }
}
In my controller:
[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
是货币值,因此应该是十进制(根据需要添加其他验证和显示属性)
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
@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方法将是
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" />
}
和将包括一个脚本添加新的CashRecipientVM
的html
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)
相关文章:
- 何时指定与主干中的集合/视图关联的模型
- 如何在 BackboneJS *木偶* 集合视图中打印行行
- EmberJS:从集合视图访问项视图
- 另一个集合视图中的集合视图
- 主干:从集合视图向集合添加模型
- 主干.js从静态 JSON 呈现集合视图
- 主干集合视图添加未使用模型调用
- 主干集合视图仅渲染集合中的最后一个对象
- 每个主干集合视图
- backbone.js-集合视图给出"TypeError:无法读取属性'el'未定义的“;错误
- Backbone.js集合视图渲染重复项
- Backbone.Marionette:将标题添加到集合视图
- 集合视图未呈现项目视图
- Backbone-简单集合视图-can't打印项目
- 当其中一个模型发生变化时,我如何在Backbone.js中为集合视图附加事件处理程序?
- 将渲染到木偶集合视图中的项目动画化
- 如何将参数传递给集合视图服务器调用
- Backbonejs+MarionetteJD-将Backbone列表视图转换为MarionetteJS集合视图
- 如何添加节到一个带有tagName: 'table'的木偶集合视图
- js集合视图不呈现模型属性