Lamloumi Afif
Lamloumi Afif

Reputation: 9081

Change html list box to Html.ListBox

i have an asp.net mvc application in which i have this Model:

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

    }

in my view i'd like to replace this snippet:

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

by another code using the html helpers Html.ListBox or Html.ListBoxFor.

How can i modify my code to do this task?

Upvotes: 0

Views: 1429

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039228

There's a difference between a dropdown list and a list box -> the list box allows for multiple items to be selected. In the example code you have shown, you haven't set the multiple="multiple" attribute on your <select> element so if you want an equivalent of this code you'd rather use an Html.DropDownList instead of an Html.ListBox as requested:

@Html.DropDownList("id_vehicule", new SelectList(Model.GetVehicleList(), "Id_vehicule", "Type"))

But I'd rather use a view model and the strongly typed version of the helper. So basically I would define a property on my view model that will hold the selected item value:

public int SelectedVehiculeId { get; set; }

I would also define a property that will hold the available items:

public SelectList Vehicules { get; set; }

that the controller action will populate:

model.Vehicules = new SelectList(GetVehicleList(), "Id_vehicule", "Type");

and then in the view:

@Html.DropDownListFor(x => x.SelectedVehiculeId, Model.Vehicules)

The idea here is that the view shouldn't be calling any methods to retrieve data. This is the responsibility of the controller when preparing the view model. The view is there only to display the data.

Upvotes: 2

Related Questions