首先,通过创建一个视图模型来代表您要编辑的内容。我假设
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 > @using (Html.BeginCollectionItem("recipients")) { @Html.HiddenFor(m => m.ID, new { @ }) @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" >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" />}并将包含用于添加新HTML的脚本
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)



