Asp.net mvc MVC5脚手架下拉框
我想查看、编辑和创建我的查找关系的下拉列表 有时候这样行,有时候不行。这是一个谜,我希望能在这里得到解决 这是我的POCO用于查找Asp.net mvc MVC5脚手架下拉框,asp.net-mvc,asp.net-mvc-5,poco,html.dropdownlistfor,asp.net-mvc-scaffolding,Asp.net Mvc,Asp.net Mvc 5,Poco,Html.dropdownlistfor,Asp.net Mvc Scaffolding,我想查看、编辑和创建我的查找关系的下拉列表 有时候这样行,有时候不行。这是一个谜,我希望能在这里得到解决 这是我的POCO用于查找 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 V
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
这是我想用颜色和大小下拉框显示的主要对象
public class Product
{
public int Id;
public string Name;
public virtual Color Color;
public virtual Size Size;
}
这对我没用。在查看、编辑或创建产品时,尺寸和颜色都不会显示。我只看到名称字段。默认情况下,大小和颜色是延迟加载的(虚拟),因此您需要急切地加载它们:
var products = context.Products.Include(p => p.Color).Include(p => p.Size).ToList();
如果您的问题是下拉列表,您将希望在控制器中组成一个包含列表项的viewmodel,将其发送到视图并使用DropDownListFor(m=>m.ColorId,m.Colors)。您可能需要将ColorId和SizeId添加到产品模型中。这里有一个很好的解释:就这样改变吧:
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;}
}
<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>
然后,只需添加带有创建或编辑模板的脚手架视图,VS将生成DDL,如下所示:
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;}
}
<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>
@LabelFor(model=>model.Color\u Id,“Color\u Id”,htmlAttributes:new{@class=“control label col-md-2”})
@DropDownList(“Color\u Id”,null,htmlAttributes:new{@class=“form control”})
@Html.ValidationMessageFor(model=>model.Color_Id,“,new{@class=“text danger”})