一个视图,用于在同一视图上添加和删除集合中的项目 [英] A view to add and remove items from a collection on the same view

查看:57
本文介绍了一个视图,用于在同一视图上添加和删除集合中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm creating a View that allows the user to add and remove objects in list in a particular way that the client wants. The user has to be able to add or remove multiple forms on the page before submitting. When the page posts it needs to display what's already in the list, with the option to remove each item, plus allow the user to add/remove more objects before submitting again.

我能够使用JQuery和Partial View来让用户在提交之前添加或删除新表单.我不知道如何提供一个按钮来从上一次提交中删除列表中已经存在的对象.

I'm able to use JQuery and a Partial View to let the user add or remove new forms before submitting. What I can't figure out is how to provide a button to remove objects that are already in the list from a previous submit.

有人可以帮我吗?将不胜感激.

Can anyone help me out with this? It would be greatly appreciated.

这是我到目前为止所发现的.在我看来:

Here's what I've figured out so far. In my 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 + '"]');
    })

具有将数据添加到新对象的表单的局部视图:

The Partial View with the form to add data to a new object:

@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; }
}

推荐答案

仅具有一个删除"按钮是没有意义的,您需要与该集合中的每个项目相关联的删除".另外,从< div> 元素中删除 id 属性,并使用相对选择器.

Having a single 'remove' button does not make sense and you need a 'remove' associated with each item in the collection. In addition, remove the id attributes from your <div> elements and use relative selectors.

将部分更改为

@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>
}

在主视图中,您的脚本将是

The in the main view, your scripts will be

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

For any items that have been added in the view, the value of property ID will be null and the code in the if block will remove the item from the view. However for existing items that you may be editing (where the ID has a value), then you need to consider how to remove it from the database. Options include

  1. 在视图模型中添加其他属性(例如) public boolIsDeleted {get;放;} ,并在部分内容中包含隐藏的输入为了它.然后可以将其设置为 true ,这样在提交时,您可以删除所有收件人.where(x => x.IsDeleted);

  1. Adding an additional property in the view model (say) public bool IsDeleted { get; set; } and including a hidden input in the partial for it. You could then set it to true so when you submit, you can delete all recipients.Where(x => x.IsDeleted);

@Html.HiddenFor(m => m.IsDeleted, new { @class = "flag" })

} else {
    container.find('.flag').val('true');
}

  • 对服务器方法进行ajax调用,该方法将从以下方法中删除项目数据库,如果成功,则删除关联的容器从DOM

  • Making an ajax call to a server method which deletes the item from the database, and if successful, remove the associated container from the DOM

    } else {
        $.post(yourDeleteUrl, { id: id }, function(response) {
            if(response) {
                container.remove()
            } else {
                // oops, something went wrong
            }
        });
    }
    

  • 这篇关于一个视图,用于在同一视图上添加和删除集合中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆