使用枚举选择从数据库填充的 Html.DropDownListFor() 的默认值
当存在以下条件时,我似乎无法在 Html.DropDownListFor 中设置所选项目:
1)所选项目 ID 是从枚举(例如,(int)AnimalType)中提取的,
2)列表是从 例如,在这个未经测试
的伪代码中,View 的 DropDownList 不会选择动物 Dog。请注意,如果我将枚举更改为生成 int 值的静态类,则没有问题。在 Linq select 语句中,如果我尝试将 a.AnimalType 转换为 (int)a.AnimalType,编译器会发出警告。有什么想法吗?
谢谢。
//--------------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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用整数作为选定的动物:
然后在控制器中:
最后在视图中:
Try using an integer as the selected animal:
and then in your controller:
and finally in the view: