Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a default value in dropdownlistfor MVC 4

I'm trying to make a dropdownlistfor with a selected value but it doesn't work :/ And I search on the web but I don't find the solution :/

For the moment, I'm doing this :

In C# :

ViewBag.ID_VEH = new SelectList(db.VEHI, "ID_VEH", "COD_VEH", 4); // 4 is an example

In my cshtml :

@Html.DropDownListFor(model => model.ID_VEH, ViewBag.ID_VEH as SelectList)

The dropdownlist is well complete but the default value is not selected :/ do you have an idea please ?

like image 254
user2609766 Avatar asked Jul 23 '13 08:07

user2609766


People also ask

Can we set default values for model?

In practice, you could create the ViewModel, and override these defaults with values pulled from a database entry (using the data-backed model), but as-is, this will always use these default values.

What is selected value in DropDownList?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.


1 Answers

What I like to do is add a list of the items to display in the dropdownlist to my model, so I don't have to pass that list via a viewbag. Also i like to add a field to my model that contains the SelectedValue, that I fill in the controller

Then you can do

@Html.DropDownListFor(model => model.ID_VEH, new SelectList(Model.listVEH, "ID_VEH", "COD_VEH", Model.SelectedVEH_ID), "--Select VEH--")
like image 190
Dylan Slabbinck Avatar answered Sep 24 '22 22:09

Dylan Slabbinck