Select a default value in dropdownlistfor MVC 4

a 夏天 提交于 2019-12-19 05:32:24

问题


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;


来源:https://stackoverflow.com/questions/17805265/select-a-default-value-in-dropdownlistfor-mvc-4

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