从视图模型填充剃刀DropDownList

时间:2013-09-28 21:52:12

标签: asp.net-mvc-4 razor

我有一个自定义模型(比方说CustomModel)用于在视图中填充我的剃刀DropDownList:

namespace MyNamespace.Models
{
    public class SelectListItem
    {
        public string Value { get; set; }
        public string Text { get; set; }
    }

    public class ComponentTypeModel
    {
        private readonly List<ComponentType> componentTypes;

        [Display(Name = "Component Type")]
        public int SelectedCompTypeId { get; set; }

        public IEnumerable<SelectListItem> CompTypeItems
        {
            get
            {
                var allCompTypes = componentTypes.Select(f => new SelectListItem
                {
                    Value = f.Id.ToString(),
                    Text = f.Name
                });

                return allCompTypes;
            }
        }

        public IEnumerable<SelectListItem> DefaultCompTypeItem
        {
            get
            {
                return Enumerable.Repeat(new SelectListItem
                                               {
                                                   Value = "-1",
                                                   Text = "Select a component type"
                                               }, 
                                         count: 1);
            }

        }
    }
}

然后在我看来,我使用剃须刀执行以下操作:

@model MyNamespace.Models.CustomModel

@Html.LabelFor(m => m.SelectedCompTypeId);
@Html.DropDownListFor(m => m.SelectedCompTypeId, Model.CompTypeItems);

但第二个参数 Model.CompTypeItems 在行中:

@Html.DropDownListFor(m => m.SelectedCompTypeId, Model.CompTypeItems);

正在生成编译错误,指出它无效。有什么想法吗?

1 个答案:

答案 0 :(得分:5)

我认为你让自己变得复杂。

只需使用此模型:

public class ComponentTypeModel
{
    public int? SelectedComp {get; set;}
    public SelectList DDLCompTypes {get; set;}
}

然后在你的控制器中:

var model = new ComponentTypeModel();
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name");

//If you need to set some value in the DropDownValue (for instance in the Edit view) you do:
model.DDLCompTypes = new SelectList(theComponentTypes, "Id","Name", model.SelectedComp);

然后在你的视图中:

@Html.DropDownFor(x => x.SelectedComp, Model.DDLCompTypes, "Select a component type" )