2010-07-13 49 views
1

我不完全確定我的lambda的尚未解決,但爲什麼不是以下工作? 4/MVC2MVC 2:如何使用Html.DropDownListFor?

作品:

// 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> 

不起作用:

// 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> 

回答

4

DropDownListFor需要(至少)兩個參數。第一個參數是將在回發中保存選定值的屬性(並且包含當前選定值),第二個參數是包含選項的鍵/值對的IEnumerable<SelectListItem>。將您的Feature屬性重命名爲FeatureMenu或其他類型,並創建與該選項的值相對應的類型的屬性名稱。然後將FeatureMenu添加到DropDownListFor的參數。

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

...

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

由於它的工作原理。但它看起來像我現在只需要解決DDL錯誤描述http://stackoverflow.com/questions/1916462/dropdownlistfor-in-editortemplate-not-selecting-value – ryan 2010-07-13 13:13:17

+0

嗯。我沒有看到這個特定的問題,但是我通常使用自定義方法返回視圖,以確保根據我返回的視圖來填充菜單。 – tvanfosson 2010-07-13 13:37:36

相關問題