views:

304

answers:

1

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

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.

Rik
That post is quite outdated. I am using MVC 2.0
Daniel A. White
I believe it is still valid in MVC 2.0, at least in preview 1
Rik