DropDownListFor - display a simple list of strings

2019-02-21 13:45发布

问题:

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?

回答1:

<%= 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) %>