Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC5 view drop down list

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

like image 333
user3736648 Avatar asked Nov 29 '22 07:11

user3736648


2 Answers

Try this;

I assume you need to fill mapLocationItem.mapLocationItemType based on the selected value when you post the data.

@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes))

If you want to add CSS class you can do it as below.

@Html.DropDownListFor(model => model.mapLocationItem.mapLocationItemType, new SelectList(Model.mapLocationItemTypes), new { @class = "your-class" })
like image 44
Saranga Avatar answered Dec 12 '22 08:12

Saranga


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.

like image 82
Kartikeya Khosla Avatar answered Dec 12 '22 08:12

Kartikeya Khosla