我正在创建一个允许用户以客户端需要的特定方式添加和删除列表中对象的视图。用户必须能够在提交之前在页面上添加或删除多个表单。当页面发布时,它需要显示列表中已有的内容,并选择删除每个项目,并允许用户在再次提交之前添加/删除更多对象。
我可以使用JQuery和部分视图让用户在提交之前添加或删除新表单。我无法弄清楚的是如何提供一个按钮来删除先前提交的列表中已有的对象。
任何人都可以帮我解决这个问题吗?非常感谢。
这是我到目前为止所发现的。 在我的观点中:
@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; }
}
答案 0 :(得分:1)
单击“删除”按钮没有意义,您需要与集合中的每个项目关联的“删除”。此外,从id
元素中删除<div>
属性并使用相对选择器。
将部分更改为
@using (Html.BeginCollectionItem("recipients"))
{
<div class="item" data-id="@Model.ID"> // add an enclosing element
@Html.HiddenFor(m => m.ID)
@Html.LabelFor(m => m.Recipient)
@Html.TextBoxFor(m => m.Recipient)
@Html.ValidationMessageFor(m => m.Recipient)
@Html.LabelFor(m => m.Amount)
@Html.TextBoxFor(m => m.Amount)
@Html.ValidationMessageFor(m => m.Amount)
<button type="button" class="remove">Remove</button> // add button
</div>
}
在主视图中,您的脚本将是
var url = '@Url.Action("Recipient")';
var recipients = $('#recipients');
$('#add').click(function () {
$.get(url, function (response) {
recipients.append(response);
});
});
$('#recipients').on('click', '.remove', (function() {
var container = $(this).closest('.item');
var id = container.data('id');
if (!id) {
container.remove();
} else {
// see notes below
}
}
对于已在视图中添加的任何项目,属性ID
的值将为null
,if
块中的代码将从视图中删除该项目。但是对于您可能正在编辑的现有项目(ID
具有值),您需要考虑如何从数据库中删除它。选项包括
在视图模型中添加其他属性(例如)public bool
IsDeleted { get; set; }
并在部分中包含隐藏的输入
为了它。然后,您可以将其设置为true
,因此当您提交时,您可以
删除所有recipients.Where(x => x.IsDeleted);
@Html.HiddenFor(m => m.IsDeleted, new { @class = "flag" })
} else {
container.find('.flag').val('true');
}
对从中删除项目的服务器方法进行ajax调用 数据库,如果成功,则删除关联的容器 来自DOM
} else {
$.post(yourDeleteUrl, { id: id }, function(response) {
if(response) {
container.remove()
} else {
// oops, something went wrong
}
});
}