Salar Afshar Salar Afshar - 1 year ago 116
C# Question

Send list of items in MVC

this is my item

public class RequestViewModel
public long FeederId { set; get; }

public int A { set; get; }

public int B { set; get; }

public int C { set; get; }

public int Remain { set; get; }

and this is my Add model that i want to send from my form to my Controller

public class RequestAddListViewModel
public List<SuppliantRequestFeederAddViewModel> SuppliantRequestFeederAddViewModels { set; get; }

public List<SelectListItem> FeederSelectListItems { set; get; }

public long NodeId { set; get; }

first time my form load i have One item i have a
when i click on it my first row clone and
to my form for example now i have 8 item on my form, i can delete each item on client side. if i didn't delete any item and submit form there no problem.
My problem is when delete one of item for example second one when deleted and then submit my form there is no item on my controller. nothing send to Controller.


@for (int index = 0; index < Model.RequestAddListViewModel.Count; index++)
var req = Model.RequestAddListViewModel[index];
<tr class="requestrow">
@Html.DropDownListFor(p => p.req[index].FeederId, Model.FeederSelectListItems, new { @class = "form-control" })
@Html.TextBoxFor(p => p.req[index].A, new { @class = "form-control" })
@Html.TextBoxFor(p => p.req[index].B, new { @class = "form-control" })
@Html.TextBoxFor(p => p.req[index].C, new { @class = "form-control" })
<button type="button" class="btn btn-primary btn-icon btn-rounded newfeeder"><i class="icon-plus2"></i></button>

and my jQuery script (Edited):

var inputCount=0;
$(document).on('click', '.newfeeder', function () {
var tr = $(this).closest("tr").clone();
tr.find("button i").removeClass("icon-plus2").addClass("icon-trash");
tr.find("input,select").each(function () {
'name': function (_, name) { return name.toString().replace('0', inputCount) },
'id': function (_, id) { return id.toString().replace('0', inputCount) }


$(document).on('click', '.deleterow', function() {

Answer Source

finally i found my solution after add or delete new item to my form i call this function ReCreateIndex()

function ReCreateIndex(container) {
    $(container).each(function (index, obj) {
        $("input,select", $(this)).each(function () {
            if ($(this).attr("name")) {
                var name = $(this).attr("name").replace($(this).attr("name").replace(/[^0-9]/gi, ''), index);
                $(this).attr("name", name);

            if ($(this).attr("id")) {
                var id = $(this).attr("id").replace($(this).attr("id").replace(/[^0-9]/gi, ''), index);
                $(this).attr("id", id);

it means that after any change on items,index of items recreated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download