我正在创建一个视图,允许用户以客户想要的特定方式添加和删除列表中的对象。用户必须能够在提交之前在页面上添加或删除多个表单。当页面发布时,它需要显示列表中已有的内容,可选择删除每个项目,并允许用户在再次提交之前添加/删除更多对象。
我可以使用 JQuery 和 Partial View 让用户在提交之前添加或删除新表单。我想不通的是如何提供一个按钮来从以前的提交中删除列表中已经存在的对象。
谁能帮我解决这个问题?这将不胜感激。
这是我到目前为止所知道的。在我看来:
@using (Html.BeginForm())
{
<div id="recipients">
@foreach (var p in Model)
{
@Html.Partial("_Recipient", p)
}
<div id="recipients0"></div>
</div>
<button id="add" type="button">Add</button>
<button id="remove" type="button">Remove</button>
<input type="submit" value="Save" />
}
<script type="text/javascript">
$('#add').click(function () {
var url = '@Url.Action("Recipient")';
var div = $('#recipients');
var divlast = $('div[id^="recipients"]:last');
var num = parseInt(divlast.prop("id").match(/\d+/g), 10) + 1;
var newdiv = $(document.createElement('div')).attr('id', 'recipients' + num)//rest of code
$.get(url, function (response) {
div.append(newdiv);
newdiv.append(response);
});
})
$('#remove').click(function () {
var div = $('#recipients');
var divlast = $('div[id^="recipients"]:last');
var num = parseInt(divlast.prop("id").match(/\d+/g), 10);
alert("div[id='recipients" + num + "']");
$("div[id='recipients" + num + "']").remove();
//div.remove('div[id^="recipients' + num + '"]');
})
带有将数据添加到新对象的表单的部分视图:
@using (Html.BeginCollectionItem("recipients"))
{
@Html.HiddenFor(m => m.ID)
@Html.LabelFor(m => m.Recipient)
@Html.TextBoxFor(m => m.Recipient)
@Html.ValidationMessageFor(m => m.Recipient)
<br />
@Html.LabelFor(m => m.Amount)
@Html.TextBoxFor(m => m.Amount)
@Html.ValidationMessageFor(m => m.Amount)
}
<td>
@Ajax.ActionLink(
"Remove",
"Remove",
"CashRecipients",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "onDeleteSuccess"
}
)
</td>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
var onDeleteSuccess = function (result) {
alert('Howdy');
};
</script>
我的控制器:
public PartialViewResult Recipient()
{
return PartialView("_Recipient", new CashRecipientViewModel());
}
// GET:
public ActionResult Create()
{
List<CashRecipientViewModel> model = new List<CashRecipientViewModel>();
return View(model);
}
// POST: CashRecipients/Create
[HttpPost]
public ActionResult Create([Bind(Include = "ID,Amount,Recipient")] IEnumerable<CashRecipientViewModel> recipients)
{
return View(recipients);
}
我的视图模型:
public class CashRecipientViewModel
{
public int? ID { get; set; }
public decimal Amount { get; set; }
[Required(ErrorMessage = "Please enter the name of the recipient")]
public string Recipient { get; set; }
}