Search code examples
javascriptasp.netasp.net-mvcasp.net-corerazor

pass data of type list<int> from Razor view(the elements were created in JS) to controller


How can I pass the data from a JS created select tags to the controller? Here is my function that creates the select tags:

function changeFunc() {
    var elements = document.getElementsByClassName('selector2');
    while (elements.length > 0) {
        elements[0].parentNode.removeChild(elements[0]);
    }
    var selector = document.getElementById('selector');
    var selectedValue = selector.value;
    console.log(selectedValue);
    @foreach (var item in Model.Rooms)
    {
            <text>
            if (@item.RoomID == selectedValue)
            {
                var selectedValue2 = @item.Capacity;
            }
            </text>
    }
    var inputContainer = document.getElementById('for-input');
    for (var i = 0; i < document.getElementById('selector').value; i++)
    {
        var selector2 = inputContainer.appendChild(document.createElement("select"));
        selector2.className = "selector2";
        var option1 = document.createElement("option");
        option1.value = "0";
        option1.text = "Choose a client";
        option1.defaultSelected = true;
        selector2.appendChild(option1);
        selector2.tagName = "ClientsIDs";
        @foreach (var item in Model.Clients)
        {
            <text>
                var optionz = document.createElement("option");
                optionz.value = @item.ID;
                optionz.text = he.decode("@item.Name");
                selector2.appendChild(optionz);
            </text>
        }
    }
}

I want to get the value from the "selector2" element. As you can see it is in a loop so it means there are many of these selectors created. That's why I want to add these values to a list. I tried to set the "name" attribute to the property of type List but the thing is that the for loop is in JS and the Model is in C# so I cannot access the index "i" variable. Here is what I tried:

selector2.name("name", @Model.Reservations2.ClientsIDs[i]);

Here is my property:

public List<int> ClientsIDs { get; set; }

Solution

  • You should set the name attribute in this way:

    selector2.setAttribute("name", "ClientsIDs[" + i +"]");
    

    Rendered Html

    enter image description here