0

我正在创建一个视图,允许用户以客户想要的特定方式添加和删除列表中的对象。用户必须能够在提交之前在页面上添加或删除多个表单。当页面发布时,它需要显示列表中已有的内容,可选择删除每个项目,并允许用户在再次提交之前添加/删除更多对象。

我可以使用 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; }
}
4

1 回答 1

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有一个值),您需要考虑如何将其从数据库中删除。选项包括

  1. 在视图模型中添加一个额外的属性(比如)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');
    }
    
  2. 对从数据库中删除项目的服务器方法进行 ajax 调用,如果成功,则从 DOM 中删除关联的容器

    } else {
        $.post(yourDeleteUrl, { id: id }, function(response) {
            if(response) {
                container.remove()
            } else {
                // oops, something went wrong
            }
        });
    }
    
于 2016-11-13T10:01:47.337 回答