开发者

asp.net mvc 3 Model with complex property and checkboxes

I have a typed view as Item (one class that i created) with a form inside to add Items to my database. This Item class has one property called Categories that is a List (Category has 2 properties ID and Name)

Im using an editorfor in my view:

<div>
     @(Html.EditorFor(e => e.Categories, "Categories"))    
</div>

I created an EditorTemplatefor called "Categories.cshtml" render all the available categories:

@{
    Layout = null;
}
@model List<Category>

@{
    foreach (Category category in ((BaseController)this.ViewContext.Controller).BaseStateManager.AvailableCategories)
    {
        @Html.Label("test", category.Name)
        <input type="checkbox" name="Categories" value="@(category.ID)" />
    }    
}

The ch开发者_运维百科eckboxes are well rendered (one for every Available category in cache), but after clicking in some, and post the form, im receiving my instance of Item but with the property Categories empty.

What i have to do to receive my List Categories completely instantiated after submit the form?


Dont loop it. Let the framework generate the code for you (then, it will know how to build it back and bind it to your controller).

Just pass the list to the editor template and mvc will do the rest. Check my blog post on something similar.


Try using an index based loop. This ensures MVC will render the item's attributes in such a way that allows the default model binder to instantiate the model on post back. Also, use the Html helper for the checkbox as well:

var categories = ((BaseController)this.ViewContext.Controller).BaseStateManager.AvailableCategories;

for (var index = 0; index < categories.Count; index ++)
{
    @Html.Label("test", categories[index].Name)
    @Html.Checkbox("ID", categories[index].ID)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜