9

我觉得有点傻。

我正在尝试使用拳击作为功能示例来掌握 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; }
}

这是拳击手物品的代码

[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))
4

1 回答 1

27

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

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
)
于 2013-01-13T14:55:01.150 回答