In a C# MVC5 Internet application view, how can I display a dropdown list for a user to select a list item that is populated from a View Model
list?
Here is the ViewModel
code:
public class MapLocationItemViewModel
{
[Editable(false)]
public int mapLocationForeignKeyId { get; set; }
public List<string> mapLocationItemTypes { get; set; }
public MapLocationItem mapLocationItem { get; set; }
}
Here is the code that I currently have in the View
:
<div class="form-group">
@Html.LabelFor(model => model.mapLocationItem.mapLocationItemType, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.mapLocationItemTypes)
</div>
</div>
Each item in the mapLocationItemTypes
is currently being displayed as a class="text-box single-line valid"
.
Is there a MVC View tag that will display a list that is populated from a list<string>
or an array
?
I have tried the following code:
@Html.DropDownListFor(model => model.mapLocationItemTypes)
However, I am getting a compilation error, and am not sure as to the value(s) for the overloaded method.
How is the best way to display a list in a view, so that the user can select an list item from the list?
Thanks in advance
Model :
public List<SelectListItem> mapLocationItemTypes { get; set; }
public int mapLocationItemVal { get; set; }
View:
@Html.DropDownListFor(m => m.mapLocationItemVal , new SelectList(Model.mapLocationItemTypes , "Value", "Text"), " -----Select List----- ")
here in above example the 3rd parameter of DropDownListFor()
i.e. " -----Select List----- "
will be the initial selected item of your dropdown with value equal to ''
.
At Controller during POST mapLocationItemVal
will have selected dropdown value.
The above shown code is best and simplest way to bind Dropdownlist in MVC.