ASP.NET MVC 2.0 - IList<T> CheckBoxes

寵の児 提交于 2020-01-15 08:40:34

问题


What is the best way to handle this:

class Option {
    int id;
    string name;
}

class QuoteItem
{
     IList<Option> options;
}

class QuoteViewModel {
     IList<Option> allOptions;
     QuoteItem quoteItem;
}

Basically, I have all the available options in allOptions. I want to have a checkbox that puts another Option (even if its just its id) into the QuoteItem.options list when it is checked. How would I accomplish this? Would it best be an IList<bool> and bind it after the fact?


回答1:


I suggest you take look at this blog entry from Phil Haack about model binding to a list

For your situation you can use simple model binding to a IEnumerable<int> options, where the values will be the id of your selected options.

your input view will then look something like this:

<form method="post" action="/QuoteItems/SetOptions">
        <input type="hidden" name="options" value="1" />
        <input type="hidden" name="options" value="4" />
        <input type="hidden" name="options" value="2" />
        <input type="hidden" name="options" value="8" />
        <input type="submit" />
    </form>

The hidden inputs contain your selected optionId's, note name attribute which is the same for each hidden input. The default model binder can bind this to a list of integers.

The thing you need to do next is adding / removing a hidden options input at client side depending on whether an item is selected in your "all-options" select control.



来源:https://stackoverflow.com/questions/2293025/asp-net-mvc-2-0-ilistt-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!