How to return Nested PartialViews (including their javascript) from an AJAX call in ASP.Net MVC

I created a tree structure of categories using nested partial views:

my index page (which displays the tree):

<div>
 Category Menu:
  <input type="button" value="1" name='selectCat_btn' />
  <input type="button" value="2" name='selectCat_btn' />
</div>

<!-- Treeview -->
<% Html.RenderPartial("ItemCats_UL", Model); %>

<div id="CatSelectorOutput">
</div>

ItemCats_UL:

<div>
 <ul id="catsTree"> 
  <% Html.RenderPartial("ItemCats_LI", Model); %>
 </ul>
</div>

<script type="text/javascript" >
$(document).ready(function() {        
    $("#catsTree").treeview();
</script>

ItemCats_LI:

<%foreach (ItemCategory itemCat in Model)
 { %>
  <li>
   <%= itemCat.Name %>
    <%if (itemCat.Children != null && itemCat.Children.Count() > 0)
      { %>
       <ul>
        <% Html.RenderPartial("ItemCats_LI", itemCat.Children); %>
       </ul>
    <%} %>
 </li>
<%} %>

Now this tree view works fine when I return the base view ("Index", "Model") from my pointers. Index action on page load.

The problem arises when I want to change the category model displayed in my Treeview (nested partial elements) from an AJAX call ...

: "Cats2", ParentID 2 Treeview. , JsonResult html ItemCats_UL PartialView ( RenderPartialToString ) . , Javascript , AJAX PartialViewResult, Javascript Treeview, RenderPartialToString.

:

<script type="text/javascript">
$("[name='selectCat_btn']").click(function() {       
    var CID = $(this).attr('value');      
    $.ajax({
        type: "POST",
        url: "SelectCat",
        dataType: "json",
        data: { "CID": CID },
        success: function(result) { $("#CatSelectorOutput").html(result.output); }
    });
    return false;
});
</script>

My Controller Action:

 [AcceptVerbs(HttpVerbs.Post)]
    [UrlRoute(Name = "SelectCat", Path = "selectCat")]
    public ActionResult SelectCat(int CID)
    {
        IQueryable<ItemCategory> cats;
        cats = ItemRepo.GetItemCats().WithCID(CID);

        JsonResult result = null;
        result = new JsonResult
        {
            Data = new
            {
                success = true,
                output =
                Helpers.RenderHelper
                .RenderPartialToString("~/Views/Admin/AdminItemCatsUL.ascx",
                cats)                    
            }
        };
        return result;
    }

:

ItemCats _UL partialView displays! BUT the nested PartialViews (ItemCats_ LI) !

, , ItemCats_UL.ascx "Html" :

<ul id="catsTree"> 
 <% Html.RenderPartial("ItemCats_LI", Model); %>
</ul>

. : viewContext
Html = 'Html' 'System.ArgumentNullException'
, , RenderPartialToString, ? - ?

+3
1

HTML/JavaScript DOM .
, , jQuery LiveQuery () .

, jQuery document.ready , :

$("#catsTree").livequery(function () { this.treeview(); }, function () { /* code to destroy the treeview here */ });
-1

Source: https://habr.com/ru/post/1721385/


All Articles