I have a big开发者_运维百科 problem, at least for me. I have a Table with categories and unlimited subcategories. The table looks like this:
ID Parent_ID Name
1 null riding
2 1 gallopa
3 null figure
4 2 trapper
And there is a table containing items wich are attributed to a category. The table looks like this:
ID cattegory_ID Name
1 4 fast
2 1 slow
3 3 high
4 2 low
Now I want to retrieve them from the database and show them in my mvc2 application like this: A Fieldset for the first category, and one for the subcategory in the fieldset before. The items should be listed in the fieldset with checkboxes. http://i.stack.imgur.com/lyMWD.png
I like to work with @Html.CheckBoxfor
.
Has any one got any idea? I'm working on this problem since last week without a result. I tried to solve the problem recursively but it did not work. An example would be beautiful, thanks a lot!
Thanks a lot for your answer! Everything works fine! But how to do a Httppost with this model? And how to get the Status Checked or not Checked of every checkbox?
here is my start:
[HttpPost]
public ActionResult CreateNewHorse(NewHorseModel collection)
{
collection.Cattegories.Count(); <------------is always null! Why?
}
You could create a PartialView that has the Category-class as a Model, something like this:
Category.cshtml
@model Category
<fieldset>
<legend>@Model.Name</legend>
@foreach (var item in Model.Choices)
{
Html.RenderPartial("Choice", item);
}
@foreach(var item in Model.Subcategories)
{
Html.RenderPartial("Category", item);
}
</fieldset>
Choice.cshtml
@model StackOverflow_Tester.Models.Choice
<p>@Html.LabelFor(m => m.Selected) @Html.CheckBoxFor(m => m.Selected)</p>
in your main view, you'd simply render the partialview based on the categories:
@foreach (var item in Model)
{
Html.RenderPartial("Category", item);
}
Now you need to pass only the root categories into your view
This should give you a recursive view with categories and/or subcategories.
UPDATE
The viewmodel/model could look like this:
Category.cs
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List<Category> Subcategories { get; set; }
public List<Choice> Choices { get; set; }
public Category Parent { get; set; }
}
Choice.cs
public class Choice
{
public int Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
I've updated the code in the top as well, to reflect this Model
Hope this helps!
精彩评论