MVC 4 Simple Populate DropDown from database model

时间:2013-01-13 14:16:56

标签: c# entity-framework asp.net-mvc-4

我觉得有点愚蠢。

我正在尝试使用拳击作为功能示例来获取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))

谢谢!

1 个答案:

答案 0 :(得分: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
)