ネストされた部分ビューを使用して、カテゴリのツリービューを作成しました。
私のインデックスページ(ツリービューを表示する):
<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>
<%} %>
このツリービューは、ページの読み込み時にコントローラーの Index アクションから基本的な View("Index", Model) を返すと完全に機能します。
Treeview (ネストされた partialViews) に表示されるカテゴリ モデルを AJAX 呼び出しから変更したい場合に問題が発生します...
例: 「Cats2」ボタンをクリックすると、ツリービューに ParentID が 2 のカテゴリがページに表示されます。コントローラ アクションからItemCats_UL PartialView の html の JsonResult を返すことでこれを試みました (ここにあるRenderPartialToStringメソッドを使用)。一部のユーザーは、AJAX フォームを使用して PartialViewResult を返すときに Javascript が部分ビューで実行されないことを知っているかもしれません。RenderPartialToString を使用している理由は、Treeview に Javascript が必要だからです。
カテゴリ選択ボタンのクリック ハンドラ:
<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>
私のコントローラーアクション:
[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>
値を null にすることはできません。パラメーター名: viewContext
Html = 'Html' が 'System.ArgumentNullException' 型の例外を
スローしました それとも、単純なものが欠けていますか?