javascriptarraysasp.net-mvcmodel-view-controller

Get Unsorted list list items that are added dynamically in the Controller


I am working on a project (MVC) with Razor views.

I am trying to populate a list dynamically (trying with ul/li but the select/option would also be fine) with a click on a button. The user is filling in a field, clicks a "add" button and this adds it to a ul/li structure.

When I am looking at the inspect element, I can see my values being added, my issue is to store them into Session["..."] ... Or in a hidden field so that I can iterate on them in the Controller action.

I tried several JS/Jquery answers from the net but none of them seemed to work in my case.

Here is how I populate the ul/li structure:

function addPrice() {

    var priceValue = $("#PriceValue").val() // this is the input that users fill in

    var ul = document.getElementById("priceListBox");
    var li = document.createElement("li");

    li.setAttribute('class', "list-group-item list-group-item-action"); // set the class for design
    li.setAttribute('id', priceValue); // set the id to be able to remove
    li.appendChild(document.createTextNode(priceValue));

    ul.appendChild(li);

}

Above correctly populates a ul with list items holding the value of the user input.

This is my hidden field attempt:

<input type="hidden" name="PriceValues" value="" runat="server"/>

This is my predefined ul:

<ul class="list-group col-md-3" id="priceListBox" name="priceListBox" runat="server"> </ul>

This is the latest attempt I tried to build up my array and access these values in the controller action:

function SetItemsToArray() {

    //const listItems = document.querySelectorAll('li');
    //for (let i = 0; i < listItems.length; i++) {
    //    alert(listItems[i].textContent);
    //}


    var listItems = document.getElementById('priceListBox').getElementsByTagName('li'), myArray = map(listItems, getText);           

    function map(arraylike, fn) {
        var ret = [], i = -1, len = arraylike.length;
        while (++i < len) ret[i] = fn(arraylike[i]);
        return ret;
    }

    function gettext(node) {
        if (node.nodetype === 3) return node.data;
        var txt = '';
        if (node = node.firstchild) do {
            txt += gettext(node);
        } while (node = node.nextsibling);

        $('#PriceValues').val(txt); // Jquery attempt
        document.getelementbyid("PriceValues").value = txt; // js attempt
    }
}

I would like to know:

Thank you all for any response, if any question ask and I will do my best to reply correctly to it.

Kind regards.


Solution

  • This worked by putting it where I add the list items dynamically

    document.getElementById("PriceValues").value += priceValue + ";";
    

    and in my controller:

    var a = Request.Form["PriceValues"];