簡體   English   中英

MVC 4 Simple Populate DropDown 從數據庫模型

[英]MVC 4 Simple Populate DropDown from database model

我覺得有點傻。

我正在嘗試使用拳擊作為功能示例來了解 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))

你可以設計一個視圖模型:

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
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM