Using an enum to choose the default value of an Html.DropDownListFor() populated from a database
I can't seem to set the Selected item in an Html.DropDownListFor when the following conditions exist:
1) The selected item ID is drawn from an enum (e.g., (int)AnimalType), and
2) The list is populated from a database (or, actually, any list other than the enum)
For example, in this untested pseudocode, the View's DropDownList would not have the animal Dog selected. Note that if I change the enum to a static class that produces int values, I have no problem. In the Linq select statement, if I try to cast a.AnimalType to (int)a.AnimalType, the compiler complains. Any ideas?
Thanks.
//--------------In the model
enum AnimalType
{
Dog = 1,
Cat = 2,
//etc.
}
public class Animal
{
public AnimalType AnimalId {get;set;}
public string Name {get;set;}
//etc.
}
public class AnimalModel
{
public AnimalId SelectedAnimal {get;set;}
public IEnumerable<SelectListItem> AllAnimals {get;set;}
}
//--------------In the controller
AnimalModel model = new AnimalModel();
model.SelectedAnimal = (AnimalType)1;
List<Animal> getAllAnimals = Repository.GetAllAnimals();//defined elsewhere
IEnumerable<SelectListItem> animalList =
开发者_如何转开发 from a in getAllAnimals
select new SelectListItem
{
Selected = (a.AnimalType == (int)model.SelectedAnimal),
Text = a.Name,
Value = a.AnimalId.ToString()
};
model.AllAnimals = animalList;
//--------------In the view
@Html.DropDownListFor(m => m.Id, Model.AllAnimals)
Try using an integer as the selected animal:
public class AnimalModel
{
public int SelectedAnimal { get; set; }
public IEnumerable<SelectListItem> AllAnimals { get; set; }
}
and then in your controller:
public ActionResult Index()
{
var animals = Repository.GetAllAnimals();
var model = new AnimalModel
{
// define which item should be selected in the drop down
SelectedAnimal = (int)AnimalType.Cat,
// define the list of items in the drop down
AllAnimals = animals.Select(x => new SelectListItem
{
Value = x.AnimalId.ToString(),
Text = x.Name
})
};
return View(model);
}
and finally in the view:
@model AnimalModel
@Html.DropDownListFor(x => x.SelectedAnimal, Model.AllAnimals)
精彩评论