MVC 4 Simple Populate DropDown from database model

后端 未结 1 1580
时光取名叫无心
时光取名叫无心 2020-12-16 19:45

I feel a bit stupid.

I\'m trying to get a hang of MVC 4, using boxing as a functional example.

I have WeightCategories in the database (H

相关标签:
1条回答
  • 2020-12-16 20:45

    You could design a view model:

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

    and then have your controller action populate and pass this view model to the view:

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

    and now your view becomes strongly typed to the view model:

    @model MyViewModel
    @Html.DropDownListFor(
        x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
        Model.WeightCategories
    )
    
    0 讨论(0)
提交回复
热议问题