Select a default value in dropdownlistfor MVC 4

2020-03-12 03:40发布

问题:

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 ?

回答1:

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


回答2:

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

In the controller:

model.ID_VEH = 4;


回答3:

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;