9

少しバカになります。

機能的な例としてボクシングを使用して、MVC4のコツをつかもうとしています。

私は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 に答える