Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formcollection only holds the selected html.listbox items values? MVC

My scenario is this: I have two listbox's, one that contains all my database items, and an empty one. The user adds the items needed from the full listbox to the empty listbox.

I'm using a form to submit all the items the user has added.

The problem is, only the selected items from the listbox are submitted. So if the user deselects some of the items, they wont be submitted in the form. My view looks like so:

<% using (Html.BeginForm("MyAction", "MyController"))
   { %>

    <%= Html.ListBox("AddedItems", Model.Items)%>

    <input type="submit" value="Submit" name="SubmitButton"/>
<% } %>

My Controller looks like so:

public ActionResult MyAction(FormCollection formCollection)
{
    var addedItems = formCollection["AddedItems"].Split(',');

    //....more code that does stuff with the items
}

Am I going about everything the wrong way? Is there better way to submit the items? What would you do?

like image 390
Darcy Avatar asked Mar 04 '10 22:03

Darcy


People also ask

What is the use of FormCollection in MVC?

Form collection is used to retrieve input elements from the controller action method. Form collection class automatically receives the data form value in controller methods in the form of key/value pair. Key and value pairs are accessed using the key name and index value.

What is form collection in ASP net?

❮ Complete Request Object Reference. The Form collection is used to retrieve the values of form elements from a form that uses the POST method.


2 Answers

I am doing this as well, I think the way I solved it is a bit more elegant. Essentially I just have a Jquery function that runs before the form post that selects all the options.

    $(function () {
        $("form").submit(function (e) {
            $("#box2View option").attr("selected", "selected");
        });
    });
like image 134
Colema18 Avatar answered Nov 16 '22 02:11

Colema18


Because it's just selectbox. You cannot post all values in selectbox. You have to use javascript to catch added items and store them in hidden input.

Un-tested code, but i think it help you.

<script type="text/javascript">
    function addItem() {
        var allItems = document.getElementById("AllItems");
        var op = allItems.options[allItems.selectedIndex];
        var hdSelectedItems = document.getElementById("hdSelectedItems");
        var lbSelectedItems = document.getElementById("lbSelectedItems");

        lbSelectedItems.options[lbSelectedItems.options.length] = op;

        if (hdSelectedItems.value != '') {
             hdSelectedItems.value += ","
        }
        hdSelectedItems.value += op.value;
    }
</script>
<%= Html.Hidden("hdSelectedItems") %>
<%= Html.ListBox("AllItems", Model.Items)%>
<%= Html.ListBox("lbSelectedItems") %>
<a href="#" onclick="addItem(); return false;">Add</a>
like image 36
cem Avatar answered Nov 16 '22 03:11

cem