views:

154

answers:

1

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  A: 
<%= 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) %>
Yakimych
Arrgh, what a stupid mistake! Now I can see a drop-down list with 2 items but they both say System.Web.Mvc.SelectListItem. It seems there's something wrong with my invocation of SelectList's constructor?
Groky
Oh yes - in the constructor you have to specify what fields you want to display in the DropDown. Otherwise what you get is the default SelectListItem.ToString().
Yakimych
Thank you, your update 2 is exactly what I was looking for :)
Groky