MVC5 Scaffolding Dropdowns Out the Box

670 views Asked by At

I want to view, edit and create with drop-down list of my lookup relationships.

Sometimes this works, sometimes it doesn't. It's a mystery that I'm hoping can be definitely solved here.

Here's my POCO's for the lookup

public class Color
{
     public int Id { get; set; }
     public string Value {get;set;}
}

//Red,White,Blue

public class Size
{
     public int Id { get; set; }
     public string Value { get; set; }
}

//S,M,L

And here is the main Object which I'd like to have the Color and Size drop-downs scaffolding to out of the box.

public class Product
{
    public int Id;
    public string Name;
    public virtual Color Color;
    public virtual Size Size;
}

This isn't working for me. Neither Size or Color are showing up when it's time to view, edit or create a Product. I only see the Name field.

2

There are 2 answers

0
Steve Greene On BEST ANSWER

Size and color are lazy loaded by default (virtual) so you need to eagerly load them:

var products = context.Products.Include(p => p.Color).Include(p => p.Size).ToList();

https://msdn.microsoft.com/en-us/data/jj574232.aspx

If your issue is with the drop downs, you will want to compose a viewmodel in your controller that has the list items, send that to your view and use DropDownListFor(m => m.ColorId, m.Colors). You may need to add ColorId and SizeId to your Product model. Here is a good explanation: http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx

0
Daniel Martínez Sarta On

Just change like this:

public class Color
{
    public int Id { get; set; }
    public string Value {get;set;}
    public ICollection<Product> Products {get;set;}
}

//Red,White,Blue

public class Size
{
     public int Id { get; set; }
     public string Value { get; set; }
     public ICollection<Product> Products {get;set;}
}

And your main object:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }

    [ForeignKey("Color")]
    public int Color_Id { get; set; }
    public virtual Color Color { get; set; }

    [ForeignKey("Size")]
    public int Size_Id { get; set; }
    public virtual Size Size { get; set; }
}

Then, just add an scaffolded View with Create or Edit templates and VS will generate the DDL like this:

 <div class="form-group">
            @Html.LabelFor(model => model.Color_Id, "Color_Id", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Color_Id", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Color_Id, "", new { @class = "text-danger" })
            </div>
 </div>