How to get all ListBox items (not just selected items) to send action to mvc

how do I get ALL ListBoxvalues ​​(not just selected items) for the submit action in the project asp.net mvc2.

I use Ajax forms like

Ajax.BeginForm("actionname", new....)

I will get all the items in the list only if I select all the items in the list.

In any case, to get all the items, not just the selected items in lisbox on the action page?

+3
source share
2 answers

This is not as easy to do as you might think, since from the html point of view, only the value selected in the drop-down list is the value sent to the server in submit.

, json jquery, .

:

,

public ActionResult MyAction(string myDropDown, string myDropDownValues)

Ajax,

@using (Ajax.BeginForm("MyAction", new AjaxOptions()))
{ 
    @Html.Hidden("myDropDownValues")
    <select name="myDropDown" id="myDropDown">
        <option value="0">First</option>
        <option value="1">Second</option>
        <option value="2">Third</option>
        <option value="3">Fourth</option>
        <option value="4">Fifth</option>
    </select>
    <input type="submit" id="submit" />
}

submit : $('form').submit(function(){});

, , . .each(), json .

json, , .

:

<script>
    $(document).ready(function () {
        $('form').submit(function () {
            var json = "";
            $("#myDropDown option").each(function () {
                value = $(this).val()
                text = $(this).html()

                if (json.length != 0) json += ",";

                json += value + ":" + text;
            });

            $('#myDropDownValues').val(json.toString());
        });
    });
</script>

, myDropDownValues :

0:First,1:Second,2:Third,3:Fourth,4:Fifth

+3

for (int i = 0; i < listBox1.Items.Count; i++) {
    listBox1.SelectedIndex = i;
    MessageBox.Show(listBox1.SelectedItem.ToString());
}
0

Source: https://habr.com/ru/post/1791412/


All Articles