A Partial View passing a collection using the Html.BeginCollectionItem helper

前端 未结 1 820
借酒劲吻你
借酒劲吻你 2020-11-21 23:07

I made a small project to understand the answer from Stephen Muecke here: Submit same Partial View called multiple times data to controller?

Almost everything works.

1条回答
  •  一向
    一向 (楼主)
    2020-11-21 23:34

    First start by creating a view model to represent what you want to edit. I'm assuming cashAmount is a monetary value, so therefore should be a decimal (add other validation and display attributes as required)

    public class CashRecipientVM
    {
        public int? ID { get; set; }
        public decimal Amount { get; set; }
        [Required(ErrorMessage = "Please enter the name of the recipient")]
        public string Recipient { get; set; }  
    }
    

    Then create a partial view (say) _Recipient.cshtml

    @model CashRecipientVM
    
    @using (Html.BeginCollectionItem("recipients")) { @Html.HiddenFor(m => m.ID, new { @class="id" }) @Html.LabelFor(m => m.Recipient) @Html.TextBoxFor(m => m.Recipient) @Html.ValidationMesssageFor(m => m.Recipient) @Html.LabelFor(m => m.Amount) @Html.TextBoxFor(m => m.Amount) @Html.ValidationMesssageFor(m => m.Amount) }

    and a method to return that partial

    public PartialViewResult Recipient()
    {
        return PartialView("_Recipient", new CashRecipientVM());
    }
    

    Then your main GET method will be

    public ActionResult Create()
    {
        List model = new List();
        .... // add any existing objects that your editing
        return View(model);
    }
    

    and its view will be

    @model IEnumerable
    @using (Html.BeginForm())
    {
        
    foreach(var recipient in Model) { @Html.Partial("_Recipient", recipient) }
    }

    and will include a script to add the html for a new CashRecipientVM

    var url = '@Url.Action("Recipient")';
    var form = $('form');
    var recipients = $('#recipients');
    $('#add').click(function() {
        $.get(url, function(response) {
            recipients.append(response);
            // Reparse the validator for client side validation
            form.data('validator', null);
            $.validator.unobtrusive.parse(form);
        });
    });
    

    and the script to delete an item

    $('.delete').click(function() {
        var container = $(this).closest('.recipient');
        var id = container.find('.id').val();
        if (id) {
            // make ajax post to delete item
            $.post(yourDeleteUrl, { id: id }, function(result) {
                container.remove();
            }.fail(function (result) {
                // Oops, something went wrong (display error message?)
            }
        } else {
            // It never existed, so just remove the container
            container.remove();
        }
    });
    

    And the form will post back to

    public ActionResult Create(IEnumerable recipients)
    

    0 讨论(0)
提交回复
热议问题