Search code examples
asp.net-mvcasp.net-mvc-5pocohtml.dropdownlistforasp.net-mvc-scaffolding

MVC5 Scaffolding Dropdowns Out the Box


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.


Solution

  • 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