Select a default value in dropdownlistfor MVC 4

ぐ巨炮叔叔 提交于 2019-12-01 03:38:34
Dylan Slabbinck

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

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

In the controller:

model.ID_VEH = 4;
real_yggdrasil

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!