Best programming practice of using DropDownList in ASP.Net MVC
Solution 1:
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"}
};
}
}
Solution 2:
I would say, completely separate dropdown items from ViewData
. Have your model contain a property for dropdown. Fill that in your controller and just bind it in the view like
ViewModel
class MyModel
{
public IEnumerable<SelectListItem> dropdowndata {get; set;}
}
Controller
public Actionresult MyAction(string id)
{
IEnumerable<data> mydata = callDALmethodtogetit();
Mymodel model = new MyModel
{
dropdowndata = mydata.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
});
}
}
View
@Html.DropDownListFor(model => model.dropdowndata, Model.dropdowndata)