Evonet
Evonet

Reputation: 3640

Error changing nested ViewModel to IEnumerable

I'm trying to create a nested ViewModel and have managed to confuse myself, I don't think the approach that I'm following is correct (also it doesn't work), so I'm hoping for some guidance.

Firstly I have a Quote Item that looks like this:

public class Quote
{

    public Quote()
    {
        this.QuoteItems = new HashSet<QuoteItem>();
    }

    [Key]
    public int QuoteID { get; set; }

    // Other properties not shown

    public ICollection<QuoteItem> QuoteItems { get; set; }
}

A quote has many QuoteItems:

public class QuoteItem
{

    [Key]
    public int QuoteItemID { get; set; }

    // Other properties not shown

    public Quote Quote { get; set; }
}

My Quote Controller uses a ViewModel called QuoteFormViewModel mainly to strongly type some drop down lists:

public class QuoteFormViewModel
{
    public Quote Quote { get; set; }

    public QuoteItemViewModel QuoteItemViewModel { get; set; }

    public IEnumerable<SelectListItem> ConstructionTypes { get; set; }
    public IEnumerable<SelectListItem> ConditionTypes { get; set; }
    public IEnumerable<SelectListItem> DesignTypes { get; set; }
}

My controller:

 QuoteFormViewModel viewModel = createViewModel(new Quote());

 viewModel.Quote.QuoteItems.Add(new QuoteItem());

In my view model you'll see I have a viewModel for my QuoteItems called QuoteItemViewModel, this is because I have an EditorFor for QuoteItems which I add to the Create and Edit forms:

@Html.EditorFor(x => x.Quote.QuoteItems)

The other reason I use QuoteItemViewModel is because a quote item will need strongly typed drop down lists as well.

My problem is that this works well but only if I add a single quote item. What I feel I need to do is in my QuoteFormViewModel change

public QuoteItemViewModel QuoteItemViewModel { get; set; }

to

public IEnumerable<QuoteItemViewModel> QuoteItemViewModels { get; set; }

But in my controller I cannot add additional items - the following code doesn't work:

viewModel.QuoteItemViewModels.Add  // Add doesn't work here...

Also on post my QuoteItems are in their seperate viewmodel, rather than added to Quote - do I need to do this manually or is there a more elegant way of doing this?

Upvotes: 0

Views: 51

Answers (2)

Loetn
Loetn

Reputation: 4040

You can't add items to a IEnumerable. You can however add items to a List.

public List<QuoteItemViewModel> QuoteItemViewModels { get; set; }

Even better is to use the interface:

public ICollection<QuoteItemViewModel> QuoteItemViewModels { get; set; }

Or you can convert your IEnumerable to a List with LINQ:

this.QuoteItemViewModels.ToList().Add(item);

Some more info.

Upvotes: 1

Andrei V
Andrei V

Reputation: 7508

You need to cast your IEnumerable to List in order to add items to your collection:

viewModel.Quote.QuoteItems.ToList().Add(new QuoteItem());

Upvotes: 1

Related Questions