ryan
ryan

Reputation: 6655

MVC 2: How to use Html.DropDownListFor?

I'm not exactly sure on my lambda's yet but why isn't the following working? 4/mvc2

Works:

// SpotlightsController.cs
public class SpotlightFormViewModel
{

    // props
    public Spotlight Spotlight { get; private set; }
    public SelectList Featured { get; private set; }
    public IDictionary<string, int> feature = new Dictionary<string, int>(){
        {"True", 1},
        {"False", 0},
    };

    // constr
    public SpotlightFormViewModel(Spotlight spotlight)
    {
        Spotlight = spotlight;
        Featured = new SelectList(feature.Keys, spotlight.Featured);
    }
}

// Edit.aspx
<div class="editor-label">
    <label for="Featured">Featured:</label>
</div>
<div class="editor-field">
    <%: Html.DropDownList("Featured", Model.Featured)%>
    <%: Html.ValidationMessage("Featured") %>
</div>

Doesn't work:

// Compiler Error Message: CS1501: No overload for method 'DropDownListFor' takes 1 arguments
// Edit.aspx
<div class="editor-label">
    <%: Html.LabelFor(model => model.Featured) %>
</div>
<div class="editor-field">
    <%: Html.DropDownListFor(model => model.Featured)%>
    <%: Html.ValidationMessageFor(model => model.Featured) %>
</div>

Upvotes: 2

Views: 5762

Answers (1)

tvanfosson
tvanfosson

Reputation: 532435

DropDownListFor takes (at least) two arguments. The first argument is the property that will hold the selected value on postback (and contains the current selected value) and the second is an IEnumerable<SelectListItem> containing the key/value pairs for the options. Rename your Feature property to FeatureMenu or something and create a property name Featured of the type corresponding to the option's value. Then add the FeatureMenu to the DropDownListFor's arguments.

 public SelectList FeatureMenu { get; private set; }
 public string Featured { get; private set; }

...

 <%: Html.DropDownListFor( model => model.Featured, Model.FeatureMenu ) %>

Upvotes: 5

Related Questions