MVC 4 Simple Populate DropDown from database model

Nic*_*ley 8 c# entity-framework asp.net-mvc-4

我觉得有点傻.

我试图获得一个MVC 4,使用拳击作为一个功能的例子.

我有WeightCategories数据库(Heavyweights等),和Boxers.

似乎很简单.关系是一个拳击手有一个当前的重量类别,但是当我编辑时,我希望它能够通过下拉来改变它.

如果它是我在代码中自己创建的列表,我理解如何做到这一点,但是我有理解如何从WeightCategory表中"加载"列表并在拳击手的视图/模型中显示它的问题.

所以,这是我的WeightCategory项目代码:

[Table("WeightCategories")]
public class WeightCategory
{
    [Key]
    public int WeightCategoryId { get; set; }

    public WEIGHT_CATEGORIES WeightCategoryType { get; set; }

    [Display(Name = "Weight Category Name")]
    [Required]
    [MinLength(5)]
    public string Name { get; set; }
    [Display(Name = "Weight Limit In Pounds")]        
    public int? WeightLimit { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是拳击手项目的代码

[Table("Boxers")]
public class Boxer
{
    [Key]
    public int BoxerId { get; set; }

    public WeightCategory CurrentWeightCategory { get; set; }

    [Required]
    public string Name { get; set; }
    public int Wins { get; set; }
    public int Losses { get; set; }
    public int Draws { get; set; }
    public int Kayos { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在视图中,我真的不确定如何解决这个问题,我很确定它不是自动的,我需要在控制器的某处加载表...我正在寻找最佳实践或其他东西.

在最后的视图中有类似的东西:

@Html.DropDownListFor(model => model.CurrentWeightCategory.WeightCategoryId,
                      new SelectList(Model.WeightCategories, "WeightCategoryId", "Name", 
                                     Model.WeightCategories.First().WeightCategoryId))
Run Code Online (Sandbox Code Playgroud)

谢谢!

Dar*_*rov 26

您可以设计一个视图模型:

public class MyViewModel
{
    public Boxer Boxer { get; set; }
    public IEnumerable<SelectListItem> WeightCategories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后填充控制器操作并将此视图模型传递给视图:

public ActionResult Edit(int id)
{
    var model = new MyViewModel();
    using (var db = new SomeDataContext())
    {
        // Get the boxer you would like to edit from the database
        model.Boxer = db.Boxers.Single(x => x.BoxerId == id);

        // Here you are selecting all the available weight categroies
        // from the database and projecting them to the IEnumerable<SelectListItem>
        model.WeightCategories = db.WeightCategories.ToList().Select(x => new SelectListItem
        {
            Value = x.WeightCategoryId.ToString(),
            Text = x.Name
        })
    }
    return View(model);
}
Run Code Online (Sandbox Code Playgroud)

现在您的视图变为对视图模型的强类型:

@model MyViewModel
@Html.DropDownListFor(
    x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
    Model.WeightCategories
)
Run Code Online (Sandbox Code Playgroud)