I'm trying to create a DropDownList
on a razor view.
Would someone help me with this?
Normal HTML5 code:
<select id="dropdowntipo">
<option value="Exemplo1">Exemplo1</option>
<option value="Exemplo2">Exemplo2</option>
<option value="Exemplo3">Exemplo3</option>
</select>
I tried this:
@{
var listItems = new List<ListItem> {
new ListItem { Text = "Exemplo1", Value = "Exemplo1" },
new ListItem { Text = "Exemplo2", Value = "Exemplo2" },
new ListItem { Text = "Exemplo3", Value = "Exemplo3" }
};
}
@Html.DropDownListFor(model =>
model.tipo,
new SelectList(listItems),
"-- Select Status --"
)
Refer:- Create drop down list in MVC 4 razor example
Here is the easiest answer:
in your view only just add:
OR in your controller add:
and your view just add:
I learned this with Jess Chadwick
Believe me I have tried a lot of options to do that and I have answer here
but I always look for the best practice and the best way I know so far for both front-end and back-end developers is
for loop
(yes I'm not kidding)Because when the front-end gives you the UI Pages with dummy data he also added classes and some inline styles on specific select option so its
hard to deal
with usingHtmlHelper
Take look at this :
this from the front-end developer so best solution is to use the for loop
fristly
create
orget your list
of data from (...) in the Controller Action and put it in ViewModel, ViewBag or whateverSecondly in the view do this simple for loop to populate the dropdownlist
in this way you will not break UI Design, and its simple , easy and more readable
hope this help you even if you did not used razor
just use This
and in View use following.
if you want to get data from Dataset and populate these data in a list box then use following code.
and in view write following code.