Assign values to the select

1

I have Brand, Blend, Flavor and Drink classes. Flavor has a Mark and a Blend. Drink consists of a Taste and other fields:

public class Brand{
  public int BrandId{ get; set; }
  public string Name{ get; set; }
  public ICollection<Flavor> Flavors { get; set; }
}

public class Blend{
  public int BlendId{ get; set; }
  public string Name{ get; set; }
  public ICollection<Flavor> Flavors { get; set; }
}

public class Flavor{
  public int FlavorId{ get; set; }
  public int BrandId{ get; set; }
  public Brand Brand{ get; set; }
  public int BlendId{ get; set; }
  public Blend Blend{ get; set; }
}

public class Drink{
  public int DrinkId{ get; set; }
  public int FlavorId{ get; set; }
  public Flavor Flavor{ get; set; }
}

I need that when creating a new drink (Views / Drink / Create.cshtml) the user selects a flavor as a string (Coca-Cola Vanilla) and not for its Id. In the case of creating a new flavor, for example, you can send Text and Value of each Brand to that of via:

ViewData["BrandId"] = new SelectList(_context.Brands, "BrandId", "Name");

but in this case it is required to access the Name field of two instances How can I do it?

    
asked by Oxagarh 05.07.2017 в 20:28
source

1 answer

1

If you need to select more than one option from the list to form the flavor you would use a listbox in the html

@Html.ListBox("BrandId", ViewBag.BrandList as MultiSelectList)

but use in the view

ViewBag.BrandList = new MultiSelectList(_context.Brands, "BrandId", "Name");

of the article

Using the DropDownList Helper with ASP.NET MVC

discusses the title "Creating a Multiple Section Select Element"

> > > my need at this time is to be able to select a single Flavor, a string composed of Brand.Name + Blend.Name

In that case you could define a property in the Flavor class that builds this string and you can use it in the select

public class Flavor
{
  public int FlavorId{ get; set; }
  public int BrandId{ get; set; }
  public Brand Brand{ get; set; }
  public int BlendId{ get; set; }
  public Blend Blend{ get; set; }

  public string FullName
  {
    get { return string.Format("{0} {1}", this.Brand.Name, this.Blend.Name);}
  }
}

then you would use

ViewBag.FlavorList = new SelectList(_context.Flavors, "FlavorId", "FullName");

As you'll see, the FullName is defined as text to show in the Flavors list

    
answered by 05.07.2017 в 21:34