2011-08-22 58 views
105

我在我的MVC3應用程序中遇到DropDownListFor問題。我能夠使用StackOverflow來找出如何讓它們出現在視圖上,但是現在我不知道如何在視圖模型提交時在視圖模型的相應屬性中捕獲這些值。爲了得到這個工作,我必須創建一個具有ID和值屬性的內部類,然後我必須使用IEnumerable<Contrib>來滿足DropDownListFor參數要求。然而,現在,MVC FW應該如何將在此下拉列表中選擇的值映射回我的視圖模型的簡單字符串屬性?MVC3 DropDownListFor - 一個簡單的例子?

public class MyViewModelClass 
{ 
    public class Contrib 
    { 
     public int ContribId { get; set; } 
     public string Value { get; set; } 
    } 

    public IEnumerable<Contrib> ContribTypeOptions = 
     new List<Contrib> 
     { 
      new Contrib {ContribId = 0, Value = "Payroll Deduction"}, 
      new Contrib {ContribId = 1, Value = "Bill Me"} 
     }; 

    [DisplayName("Contribution Type")] 
    public string ContribType { get; set; } 
} 

在我看來,我把下拉頁面上是這樣的:

<div class="editor-label"> 
    @Html.LabelFor(m => m.ContribType) 
</div> 
<div class="editor-field"> 
    @Html.DropDownListFor(m => m.ContribTypeOptions.First().ContribId, 
      new SelectList(Model.ContribTypeOptions, "ContribId", "Value")) 
</div> 

當我提交表單ContribType爲空(當然)。

這樣做的正確方法是什麼?

回答

157

你應該這樣做:

@Html.DropDownListFor(m => m.ContribType, 
       new SelectList(Model.ContribTypeOptions, 
           "ContribId", "Value")) 

其中:

m => m.ContribType 

就是結果值將是一個性質。

+1

謝謝你!謝爾蓋,這正是我一直在尋找的好幾個小時。 –

+0

感謝:)你的答案有沒有什麼辦法從這裏顯示「 - 選擇 - 」。 ? – kbvishnu

+1

@VeeKeyBee,您可以添加新項目到'contribTypeOptions'列表中,例如'new Contrib {ContribId = -1,Value =「請選擇}},它將顯示在下拉列表中。比你可以檢查'ContribType'是否爲'-1'這意味着用戶沒有選擇任何值 –

6

對於一個DropDownList綁定動態數據,你可以做到以下幾點:

在控制器像下面

ViewBag.ContribTypeOptions = yourFunctionValue(); 

現在在視圖中使用這個值象下面這樣創建ViewBag:

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
        "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please") 
6

我認爲這將有助於: 在控制器獲取列表項和選定的值

public ActionResult Edit(int id) 
{ 
    ItemsStore item = itemStoreRepository.FindById(id); 
    ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(), 
             "Id", "Name",item.CategoryId); 

    // ViewBag to pass values to View and SelectList 
    //(get list of items,valuefield,textfield,selectedValue) 

    return View(item); 
} 

,並查看

@Html.DropDownList("CategoryId",String.Empty) 
+5

通常情況下,你的版本庫不是上帝的模式。 –

0
 @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values") 

這裏的價值是模型的那個對象,你要保存選定值