2011-11-01 73 views
5

我知道這個問題已經被問到相當分配在SO上。ListBoxFor不綁定我的viewmodel

herehere

但我仍然無法找出問題。

我正在開發一個博客來教自己MVC框架。現在,當我發佈下面的視圖時,ListBoxFor助手不會將任何值綁定到我的模型。該列表成功包含所有類別,但是當POST控制器取回視圖模型時,Categories對象爲null。

這裏是視圖模型:

public class PostViewModel 
{ 
    public Post Posts { get; set; } 
    public IEnumerable<Category> Categories { get; set; } 
} 

控制器:

public ActionResult Create() 
    { 
     PostViewModel post = new PostViewModel(); 
     post.Categories = db.ListCategories(); 
     return View(post); 
    } 

的觀點:

<p>@Html.ListBoxFor(model => model.Categories, new MultiSelectList(Model.Categories, "CategoryID", "CategoryName"))</p> 
+0

您是否在POST操作中獲取了空值,或者當您嘗試在POST操作之後呈現相同的視圖? – epzee

回答

9

我相信你應該在你的視圖模型有一個數組屬性,該屬性選定的ID將綁定到。

public class PostViewModel 
{ 
    public Post Posts { get; set; } 
    public int[] SelectedCategoryIds { get; set; } 
    public IEnumerable<Category> Categories { get; set; } 
} 

,改變你的Html.ListBoxFor呼叫是爲SelectedCategoryIds財產。

<p>@Html.ListBoxFor(model => model.SelectedCategoryIds, new MultiSelectList(Model.Categories, "CategoryID", "CategoryName"))</p> 

順便說一句:現在你正在創建的SelectedCategoryIds屬性列表框,如果你有列表中的標籤,你應該改變這是爲SelectedCategoryIds財產了。

@Html.LabelFor(model => model.SelectedCategoryIds, "Categories") 

"Categories"是標籤文本)

+0

+1這真的幫了我幾個viewmodel概念 – PhilPursglove

+0

@fsmmu你的PostViewModel不應該包裝一個類別列表,這是一個域模型。 – Elisabeth

2

不是100%肯定,如果我明白你的問題;但這段代碼有幫助嗎?它顯示瞭如何在將表單發送回服務器時獲取選擇哪些類別。

[HttpPost] 
public ActionResult Create(Post post, FormCollection formCollection) 
{ 
    var listOfCategoryIDs = formCollection["categories"]; 
    var arrayOfCategoryIDs = listOfCategoryIDs.Split(','); 
}