Mark
Mark

Reputation: 7818

Asp.Net MVC Adding two viewmodels to a third

I have two viewmodels, VM1 and VM2 - I want to add these to a third viewmodel, so I can send two tables of information, to my view - but I'm struggling.

My viewmodels are:

public class VM1
{
    public string contactf { get; set; }
    public string contacts { get; set; }
}

public class VM2
{
    public string petname { get; set; }
    public string type { get; set; }
}

public class VM3
{
    public VM1 VM1 { get; set; }
    public VM2 VM2 { get; set; }

}

In my controller I have a list of contacts and a list of petnames and types:

var contacts = db.Contacts.Where(x => x.status != "Resolved")
             .Select(x => new VM1
            {
                contactf = x.contactf,
                contacts = x.contacts
            }.ToList();

var pets= db.Pets.Where(x => x.status != "Resolved")
             .Select(x => new VM2
            {
                petname = x.petname,
                type = x.type
            }.ToList();

All I want to do, is add these two lists, to the VM3 viewmodel, so I can have 2 separate lists of information sent to my view:

VM3 vm = new VM3();
vm.VM1 = contacts();

However, in the last line above, I am getting the error:

Cannot implicitly convert type 'System.Collections.Generic.List<bm.Models.VM1>' to 'bm.Models.VM1'

How can I add these two lists, to VM3 ?

Thank you,

Mark

Upvotes: 0

Views: 144

Answers (2)

Daniel Sklenitzka
Daniel Sklenitzka

Reputation: 2236

Contacts is of Type List<MV1>, thus you can't assign it to a Property of type VM1.

You need to change the definition of VM3 to:

public class VM3
{
    public List<VM1> VM1 { get; set; }
    public List<VM2> VM2 { get; set; }    
}

Upvotes: 3

Tristan
Tristan

Reputation: 352

Rewrite your VM3 class to:

public class VM3
{
  public List<VM1> VM1 { get; set; }
  public VM2 VM2 { get; set; }
}

Upvotes: 0

Related Questions