[MVC 4从数据库模型简单填充下拉列表

问题描述 投票:8回答:1

我有点傻。

我试图用拳击作为功能示例来掌握MVC 4。

我在数据库中有WeightCategoriesHeavyweights等,还有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; }
}

这里是拳击手的代码

[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; }
}

在视图中,我真的不确定如何解决这个问题,我很确定它不是自动的,我可能需要将表加载到控制器中的某个位置,也许……我正在寻找最佳实践之类的东西。

类似于最后视图中的内容:

@Html.DropDownListFor(model => model.CurrentWeightCategory.WeightCategoryId,
                      new SelectList(Model.WeightCategories, "WeightCategoryId", "Name", 
                                     Model.WeightCategories.First().WeightCategoryId))
c# entity-framework asp.net-mvc-4
1个回答
26
投票

您可以设计视图模型:

public class MyViewModel
{
    public Boxer Boxer { get; set; }
    public IEnumerable<SelectListItem> WeightCategories { get; set; }
}

然后让您的控制器动作填充并将此视图模型传递给视图:

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);
}

现在,您的视图被强类型化为视图模型:

@model MyViewModel
@Html.DropDownListFor(
    x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
    Model.WeightCategories
)

推荐问答