开发者

how to get all ListBox items(not only selected items) on submit action in mvc

how I get ALL ListBox values (not only selected items) on submit action in an asp.net mvc2 project.

I'm usin开发者_JAVA百科g Ajax forms like

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

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

Is there anyway to get all items, not only selected items in the lisbox in action page?


That is not quite as easily done as you might think, since from the html-point of view, only the value that is selected in a drop down list is the value sent to the server on a submit.

However, if it is an alternative for you to send your data as json using jquery you can serialize the list box and send it over to the action along with your model.

One way to do it is like this:

Imagine you have the following Action in any given controller

public ActionResult MyAction(string myDropDown, string myDropDownValues)

And you have this Ajax form that you want to submit

@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" />
}

What you want to do now is hook into the submit event on the form like this: $('form').submit(function(){});

You should probably use a better selector if you have multiple forms on your page. Inside this submit event you can loop through your drop down list by using the .each() method and then compose the json inside that.

Once you've created your json you can add this to a hidden field to make it easier to handle on the server side.

It could end up looking sometwhat like this:

<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>

when I submit my form now the string myDropDownValues has the following content:

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


Try this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜