2011-11-01 103 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(','); 
}