Question

How would I go around to translate this piece of code which is based on a ViewBag foreach that produces pure HTML. To a Html.DropDownList based on a Model?

My HTML right now looks like this

<select id="drpProject" name="drpProject">
       <option value="Blank" selected="selected">-- Select Project --</option>
       @foreach (SolutionName.ViewModel.project project in ViewBag.lstProject)
       {
           <option value="@project.id">@project.projectName</option>
       }
</select>

But I want to use @Html.DropDownList or @Html.DropDownListFor since I'm using @Html.TextBoxFor for my textboxes but not for my dropdownlists

Like I want this instead

@Html.DropDownListFor(x => x.projectID)

The model in question is @Model.projectID which is an integer But I want to display the projectName while the value is the projectID. I also would like to have a blank option at the start as default if it is possible with @Html.DropDownList?

Here is the controller code

List<project> lstProject = projectModel.getSetProjectCache(); //Get from SQL function
ViewBag.lstProject = lstProject;
Was it helpful?

Solution

In the controller create the viewbag like below

ViewBag.lstProject = new SelectList(lstProject,"projectID","projectName");

Now in the view just use below,You will get the dropdown as expected nothing more is needed

@Html.DropDownListFor(x => x.projectID,ViewBag.lstProject as SelectList,"")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top