C# 将html列表框更改为html.ListBox

C# 将html列表框更改为html.ListBox,c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Razor,我有一个asp.net mvc应用程序,其中包含以下模型: public class Vehicule { private string matricule; private int id_vehicule; private string type; private string chauffeur; public int Id_vehicule { get {

我有一个asp.net mvc应用程序,其中包含以下模型:

 public class Vehicule
    {

        private string matricule;
        private int id_vehicule;
        private string type;
        private string chauffeur;

        public int Id_vehicule
        {
            get { return id_vehicule; }
            set { id_vehicule = value; }
        }

        public string Matricule
        {
            get { return matricule; }
            set { matricule = value; }
        }


        public string Type
        {
            get { return type; }
            set { type = value; }
        }


        public string Chauffeur
        {
            get { return chauffeur; }
            set { chauffeur = value; }
        }

    }
在我看来,我想替换这个片段:

<select name="id_vehicule" >
@foreach(Vehicule v in Model.GetVehicleList()){
<option value="v.Id_vehicule">v.Type</option>
}
</select>

@foreach(Model.GetVehicleList()中的车辆v){
v、 类型
}
通过使用html帮助程序
html.ListBox
html.ListBoxFor
的其他代码


如何修改代码以执行此任务?

下拉列表和列表框之间存在差异->列表框允许选择多个项目。在您显示的示例代码中,您没有在
元素上设置
multiple=“multiple”
属性,因此,如果您想要与此代码等效的代码,您最好使用Html.DropDownList,而不是请求的Html.ListBox:

@Html.DropDownList("id_vehicule", new SelectList(Model.GetVehicleList(), "Id_vehicule", "Type"))
但我更愿意使用视图模型和helper的强类型版本。因此,基本上我会在视图模型上定义一个属性,该属性将保存选定项的值:

public int SelectedVehiculeId { get; set; }
我还将定义一个包含可用项的属性:

public SelectList Vehicules { get; set; }
控制器操作将填充:

model.Vehicules = new SelectList(GetVehicleList(), "Id_vehicule", "Type");
然后在视图中:

@Html.DropDownListFor(x => x.SelectedVehiculeId, Model.Vehicules)
这里的想法是视图不应该调用任何方法来检索数据。这是控制器在准备视图模型时的职责。该视图仅用于显示数据