Adding partial view within partial view

193 views Asked by At

I am currently working with MVC4. In my Database I have a table called Categories with a recursive relationship to ParentCategory. Now I want the User to be able to choose a Category, a Sub-category, a Sub-Sub-Category... and so on. How can I add Partial Views dynamically by the result of another? Displaying and evaluating a single Partial View is no problem. What I currently have is: View:

<script> 
$(document).ready(function () {
   $('#CategoryDropDown').change(function () {
   var CategoryId = $("#CategoryDropDown").val();
   $("#CascadingCategories").load('@(Url.Action("CategoryIndexChanged", "Database", null, Request.Url.Scheme))?CategoryId=' + CategoryId);
   });
});
</script>

    <!-- random markup -->

<div id="CascadingCategories">
 <p>
   <span style="width:150px; display:inline-block; line-height:42px;">Category:</span>
    @{Html.RenderPartial("_PartialCascadingCategoryDropDown", Model);}   
</div>

Partial View:

@Html.DropDownList("CategoryDropDown", new SelectList(Model.Categories, "CategoryId", "CategoryDescription"), "Select a Category", new { @class = "form-control" })

Controller:

public ActionResult CategoryIndexChanged(int? CategoryId)
{
    SearchModel model = new SearchModel();
    model.GetCategoryDropDownItems(CategoryId ?? 0);
    return PartialView("__PartialCascadingCategoryDropDown", model);
}

My idea was now to call the partial view recursive like:

<!-- this will ofc result in an infinite loop-->@{//Html.RenderPartial("_PartialCascadingCategoryDropDown", Model);}}

, but only as soon as the predecendant list has changed.

Some thoughts and problems:

  • the DropDownList will always have the same name which will make it hard to read it out
  • it's not best practice to add javascript to the partial view
  • Because I want to stay flexible over years I dislike the approach to simply add like 5 or 10 fields for RootCategoryDropDown, FirstLevelCategoryDropDown, SecondLevelCategoryDropDown, and so on.

What would help me:

  • a possibility to check within the view whether the selected category has children
  • any idea that takes a completely different approach
  • any idea on how to ADD (not load) a partial view dynamically.

Thx in advance!

0

There are 0 answers