Select a default value in dropdownlistfor MVC 4
Asked Answered
G

3

10

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 ?

Gallic answered 23/7, 2013 at 8:37 Comment(0)
M
12

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--")
Matrilateral answered 23/7, 2013 at 9:13 Comment(0)
B
9

just set the initial value of model.ID_VEH to 4:

In the controller:

model.ID_VEH = 4;
Burier answered 23/7, 2013 at 9:6 Comment(1)
this is definitely the best approach, and probably the simplestElinorelinore
B
1

Just in case someone has similar problems finding the answer:

I want to have view with the dropdown boxes have focus on the items i give (hardcoded) in the controller:

Controller:

SGLDataRegistration.Models.DataRegistrationModel mdl = rwd.GetData(DateTime.Now.Year, currentWeek, DateTime.Now, 139, 1);

View:

                    <div id="tempCustomerselect">
                        @Html.LabelFor(m => m.CustomerName)
                        @Html.DropDownListFor(m => m.PitchID, new SelectList((new SGLDataRegistration.Models.CustomerModel().GetRoles()).OrderBy(x => x.CustomerName), "PitchID", "CustomerName"), new {id = "ddlCustomer", @class="jsddlCustomer"})

                    </div>

In this GetData, i setthe desired values hardcoded:

public SGLDataRegistration.Models.DataRegistrationModel GetData(int year, int weekNumber, DateTime datum, int pitchID, int parameter) { try { DataRegistrationParameters drp = GetParameter(parameter);

        //vul een instantie van het dataregistrationmodel
        SGLDataRegistration.Models.DataRegistrationModel drm = new Models.DataRegistrationModel();
         drm.WeekNumber = weekNumber;
         drm.BeginDay = datum;
         drm.Parameter = parameter;
         drm.Year = year;
         drm.PitchID = pitchID;
Britten answered 3/1, 2014 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.