I know there are many similar questions already, but I've spent hours trying to figure this out and none of the other answers seem to help!
I want to just display a list of strings in a drop-down list using MVC. Is this really so difficult? I don't have a "Text" and "Value" separation (athough MVC appears to require one) - the string displayed to the user is my value.
I've got the following so far:
Controller:
public ActionResult Index()
{
return View(new HomeViewModel());
}
ViewModel:
public class HomeViewModel
{
public HomeViewModel()
{
Items = new SelectList(new[]
{
new SelectListItem { Text = "One", Value = "One" },
new SelectListItem { Text = "Two", Value = "Two" },
});
}
public SelectList Items { get; set; }
}
View:
<% using (Html.BeginForm()) { %>
<% Html.DropDownListFor(x => x.Items, Model.Items); %>
<input type="submit" value="Go!" />
<% } %>
But nothing I do seems to result in a drop down list being displayed. What am I doing wrong?
<%= Html.DropDownListFor(x => x.Items, Model.Items) %>
You are confusing expressions and statements. The Html helper returns a string, thus you need to use =
to output the 'html-value' (and no ;
after it).
Update:
Items = new SelectList(new[]
{
new SelectListItem {Text = "One", Value = "One"},
new SelectListItem {Text = "Two", Value = "Two"},
}, "Text", "Value");
Update 2:
Actually for your case you might do it in an even simpler fashion:
public class HomeViewModel
{
public HomeViewModel()
{
Items = new SelectList(new[] { "One", "Two" });
CurrentItem = "Two";
}
public SelectList Items { get; set; }
public string CurrentItem { get; set; }
}
And in the View:
<%= Html.DropDownListFor(x => x.CurrentItem, Model.Items) %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With