Goober
Goober

Reputation: 13506

C# Asp.Net MVC - Combine Select Lists?

I have these two methods below. One returns a list of manufacturers based on the handset ID and the other returns a list of Handsets based on the Handset ID (relationship via handset ID). How can I combine them to return one select list with the combined manufacturer handset value? (Bit new to MVC)

SelectList GetManufacturers()
{
        var manufacturers = ((DataPage<Manufacturer>)ViewData["Manufacturers"]).Records;
        return new SelectList(manufacturers, "ID", "Name", ViewData.Model.HandsetID != null ? ViewData.Model.HandsetID : -1);
}

SelectList GetHandsets()
{
    var list = ((DataPage<Handset>)ViewData["Handsets"]).Records;
    return new SelectList(list, "ID", "Name", ViewData.Model.HandsetID != null ? ViewData.Model.HandsetID : -1);
}

Help greatly appreciated,

Kind regards

Upvotes: 2

Views: 3518

Answers (2)

Robert Harvey
Robert Harvey

Reputation: 180858

The following code should work. It performs an inner join on your two lists, and then concatenates the manufacturer name and handset names of each record, with a space in between.

var manufacturers = ((DataPage<Manufacturer>)ViewData["Manufacturers"]).Records;
var handsets = ((DataPage<Handset>)ViewData["Handsets"]).Records;

var list = 

     from manufacturer in manufacturers
     join handset in handsets on manufacturer.HandsetID equals handset.HandsetID
     select new 
     { 
         ID = handset.HandsetID,
         Name = manufacturer.Name + " " + handset.Name
     };
return new SelectList(list, "ID", "Name", ViewData.Model.HandsetID != null ? ViewData.Model.HandsetID : -1);

Upvotes: 2

jao
jao

Reputation: 18620

If this is from a database, you should concatenate both fields (Manufacturer and Handset).

In linqtosql this goes like:

var result = (from foo in db.foos 
                 select new {
                             ID = foo.ID
                             Name = foo.Manufacturer + " " + foo.Handheld,
                            });

You can then use the result to fill your selectlist

Upvotes: 1

Related Questions