使用枚举选择从数据库填充的Html.DropDownListFor()的默认值

时间:2011-10-04 22:07:00

标签: asp.net-mvc c#-4.0

当存在以下条件时,我似乎无法在Html.DropDownListFor中设置Selected项:

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)

1 个答案:

答案 0 :(得分:0)

尝试使用整数作为选定的动物:

public class AnimalModel
{
    public int SelectedAnimal { get; set; }
    public IEnumerable<SelectListItem> AllAnimals { get; set; }
}

然后在你的控制器中:

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

最后在视图中:

@model AnimalModel

@Html.DropDownListFor(x => x.SelectedAnimal, Model.AllAnimals)