MVC 4 Simple Populate DropDown from database model c# entity-framework


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 (Heavyweights, etc), and Boxers.

Seem simple. The relation is a boxer has a current weight category, but when I edit, I want it to be able to change it with a drop down.

I understand how to do it if it's a list I've made myself in the code, but I have problem understanding how to "load" the list from the WeightCategory table and show it in the view/model of the boxer.

So, here is my code for the WeightCategory item:

public class WeightCategory
    public int WeightCategoryId { get; set; }

    public WEIGHT_CATEGORIES WeightCategoryType { get; set; }

    [Display(Name = "Weight Category Name")]
    public string Name { get; set; }
    [Display(Name = "Weight Limit In Pounds")]        
    public int? WeightLimit { get; set; }

Here is the code for the boxer item

public class Boxer
    public int BoxerId { get; set; }

    public WeightCategory CurrentWeightCategory { get; set; }

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

In the view, I'm really not sure how to tackle that, I'm pretty sure it's not automatic and I need to load the table somewhere in the controller maybe... I'm looking for best practice or something.

Something like that in the view at the end:

@Html.DropDownListFor(model => model.CurrentWeightCategory.WeightCategoryId,
                      new SelectList(Model.WeightCategories, "WeightCategoryId", "Name", 
1/21/2020 2:09:46 PM

Accepted Answer

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
    x => model.Boxer.CurrentWeightCategory.WeightCategoryId,
1/13/2013 2:55:01 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow