Best programming practice of using DropDownList in ASP.Net MVC

You want to use option 1, mainly because you want to use Strongly Type as much as possible, and fix the error at compile time.

In contrast, ViewData and ViewBag are dynamic, and compile could not catch error until run-time.

Here is the sample code I used in many applications –

Model

public class SampleModel
{
    public string SelectedColorId { get; set; }
    public IList<SelectListItem> AvailableColors { get; set; }

    public SampleModel()
    {
        AvailableColors = new List<SelectListItem>();
    }
}

View

@model DemoMvc.Models.SampleModel
@using (Html.BeginForm("Index", "Home"))
{
    @Html.DropDownListFor(m => m.SelectedColorId, Model.AvailableColors)
    <input type="submit" value="Submit"/>

}

Controller

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new SampleModel
        {
            AvailableColors = GetColorListItems()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(SampleModel model)
    {
        if (ModelState.IsValid)
        {
            var colorId = model.SelectedColorId;
            return View("Success");
        }
        // If we got this far, something failed, redisplay form
        // ** IMPORTANT : Fill AvailableColors again; otherwise, DropDownList will be blank. **
        model.AvailableColors = GetColorListItems();
        return View(model);
    }

    private IList<SelectListItem> GetColorListItems()
    {
        // This could be from database.
        return new List<SelectListItem>
        {
            new SelectListItem {Text = "Orange", Value = "1"},
            new SelectListItem {Text = "Red", Value = "2"}
        };
    }
}

Leave a Comment