如何绑定匿名类值的下拉列表

时间:2013-05-18 10:56:10

标签: asp.net-mvc-3 razor anonymous-function anonymous-types anonymous-class

我想填充值为A,Band C的下拉列表。以下代码仅适用于创建,不适用于编辑。

 ViewBag.UserType = new[] { new SelectListItem { Text = "A", Value = "1", Selected = false }, new SelectListItem { Text = "B", Value = "2", Selected = false }, new SelectListItem { Text = "C", Value = "3", Selected = false } };

所以我创建了一个匿名类。我有一个像下面这样的匿名课程。

var Roles= new[]
            {    new { Id =1,UserType="A" },
                 new {Id=2,UserType="B" },
                 new {Id=3,UserType="B" }            
            };
          ViewBag.Type = Roles.ToList();

但我不知道如何填写View中的下拉列表。

@Html.DropDownListFor(model => model.UserType, ((IEnumerable<SelectListItem>)ViewBag.UserType).Select(option => new SelectListItem
                                     {
                                         Text = (option == null ? "None" : option.Text),
                                         Value = option.Value.ToString(),
                                         Selected = (Model != null) && (option.Value == (Model.UserType).ToString())
                                     }),"Select")

我应该在视图中做出哪些更改

1 个答案:

答案 0 :(得分:0)

将以下属性添加到ViewModel类 -

    public SelectList Roles
    {
        get
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem
            {
                Value = "1",
                Text = "A",
            });
            items.Add(new SelectListItem
            {
                Value = "2",
                Text = "B",
            });
            items.Add(new SelectListItem
            {
                Value = "3",
                Text = "C",
            });

            return new SelectList(items, "Value", "Text");
        }
    }

    public int SelectedRole { get; set; }

并在View中绑定如下 -

    @Html.DropDownListFor(model => model.SelectedRole, Model.Roles)