问题描述:

I have a custom model (let's say CustomModel) for populating my razor DropDownList in the view:

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

}

}

}

}

Then in my view I do the following using razor:

@model MyNamespace.Models.CustomModel

@Html.LabelFor(m => m.SelectedCompTypeId);

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

but the second argument Model.CompTypeItems in line:

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

is generating a compilation error saying that it is not valid. Any ideas?

网友答案:

I think you are complicating yourself.

Just use this model:

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

Then in your controller:

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

Then in your View:

@Html.DropDownFor(x => x.SelectedComp, Model.DDLCompTypes, "Select a component type" )
相关阅读:
Top