How to dynamically create/remove elements and allow model binding to kick in?

后端 未结 3 1164
不知归路
不知归路 2021-01-01 05:20

I\'ve done this in the past, and i may have to do it again, but before i do, i want to throw it out there to see how people handle it.

Razor view:

&l         


        
3条回答
  •  梦谈多话
    2021-01-01 06:07

    I'm assuming that these things have a primary key Id field?

    Not sure it is the best way, but I have a hidden input field called, for example, deletedIds. While rendering the input element I add an attribute like:

    data-rowId='@Model.Id'
    

    And then when they click delete I add the id to the hidden list OR I mark the row as deleted with a css class and scoop them up at the end, before submit, for example:

    var deletedIds = [];
    $('myselector').each(function(){ deletedIds.push($(this).attr('data-rowId'));});
    $('deletedIds').val(deletedIds.join(','));
    

    Then split the string back to an array on the server.

    If you are dealing with them positionally and you are sure that the sequence on the server cannot change between requests, then I would use the same approach but using the index of the array rather than the id.

提交回复
热议问题