在同一视图上从集合中添加和删除项目的视图
A view to add and remove items from a collection on the same view
我正在创建一个视图,允许用户以客户需要的特定方式在列表中添加和删除对象。用户必须能够在提交之前在页面上添加或删除多个表单。当页面发布时,它需要显示列表中已有的内容,可以选择删除每个项目,并允许用户在再次提交之前 add/remove 更多对象。
我可以使用 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; }
}
只有一个 'remove' 按钮没有意义,您需要一个 'remove' 与集合中的每个项目相关联。此外,从 <div>
元素中删除 id
属性并使用相对选择器。
将偏音改为
@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
}
});
}
我正在创建一个视图,允许用户以客户需要的特定方式在列表中添加和删除对象。用户必须能够在提交之前在页面上添加或删除多个表单。当页面发布时,它需要显示列表中已有的内容,可以选择删除每个项目,并允许用户在再次提交之前 add/remove 更多对象。
我可以使用 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; }
}
只有一个 'remove' 按钮没有意义,您需要一个 'remove' 与集合中的每个项目相关联。此外,从 <div>
元素中删除 id
属性并使用相对选择器。
将偏音改为
@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 } }); }