Asp.net-Mvc

ASP.NET MVC 2 - Html.DropDownList 與 ViewModel 混淆

  • February 21, 2010

我對如何在 ASP.NET MVC 2.0 R2 上使用新的強類型 Html.DropDownListFor 助手感到完全迷失和困惑

在我寫的視圖中:

<%= Html.DropDownListFor(m => m.ParentCategory, new SelectList(Model.Categories, "CategoryId", "Name", Model.ParentCategory), "[ None ]")%>

<%= Html.ValidationMessageFor(m => m.ParentCategory)%>

我的模型對像是這樣的:

public class CategoryForm : FormModelBase
{
   public CategoryForm()
   {
       Categories = new List<Category>();

       Categories.Add(new CategoryForm.Category() {
                          CategoryId = 1, 
                          Name = "CPUs" });
       Categories.Add(new CategoryForm.Category() { 
                          CategoryId = 2, 
                          Name = "Memory" });
       Categories.Add(new CategoryForm.Category() { 
                          CategoryId = 3, 
                          Name = "Hard drives" });
   }

   // ...other props, snip... //

   public Category ParentCategory { get; set; }

   public IList<Category> Categories { get; protected set; }

   public class Category
   {
       public int? CategoryId { get; set; }
       public string Name { get; set; }
   }
}

問題是當我從下拉列表中選擇一個項目時,比如第一個項目,我收到以下 ValidationMessageFor 錯誤“值 ‘1’ 無效。”

所以我將視圖更改為…

<%= Html.DropDownListFor(m => m.ParentCategory.**CategoryId**, 
                             new SelectList .../ snip  ) %>

現在它起作用了,有點。我的 ViewModel 中的 ParentCategory 屬性設置為正確的“CategoryId”,但“名稱”為 NULL。我是否最好只為 ParentCategory 屬性設置一個可為空的 int 而不是強類型的“類別”對象?

我也遇到了同樣的問題。

例如,當我調試 Action 並查看 ModelState.Values[1].Errors[0].Exception 時,我看到以下內容:

{“從類型’System.String’到類型’System.Collections.Generic.KeyValuePair’的參數轉換`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System. Int64, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]’ 失敗,因為沒有類型轉換器可以在這些類型之間轉換。”} System.Exception {System.InvalidOperationException}

在我的場景中,我的 SelectList 是從 Dictionary 創建的,我在視圖中使用它:

<%=Html.DropDownListFor(x => x.MyDictionary, 
                            new SelectList(
                                Model.MyDictionary, 
                                "Value", 
                                "Key")) %>

當我將其更改為:

<%=Html.DropDownListFor(x => x.MyDictionary.Keys, // <-- changed to .Keys
                            new SelectList(
                                Model.MyDictionary, 
                                "Value", 
                                "Key")) %>

它工作沒有問題。

謝謝你。

引用自:https://stackoverflow.com/questions/2306527