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

前端 未结 3 581
刺人心
刺人心 2020-12-29 08:38

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 list

相关标签:
3条回答
  • 2020-12-29 09:28

    Why not have the list of items in checkboxes. Then you could iterate through the checkboxes in your action and grab all selected checkboxes.

    <% foreach(var item in Model.Items) { %>
    
       <%= Html.CheckBox(String.Format("ItemID.{0}", item.ID)) %> // each item tagged by the items id
    
    <% } %>
    
    public ActionResult MyAction(FormCollection formCollection)
    {
    
                foreach (var key in collection.AllKeys.Where(k => !k.Contains("SubmitButton")).ToArray<string>())
                {
                     // iterates thru check boxes we got rid of the button 
    
                }
    }
    
    0 讨论(0)
  • 2020-12-29 09:34

    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>
    
    0 讨论(0)
  • 2020-12-29 09:40

    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");
            });
        });
    
    0 讨论(0)
提交回复
热议问题