2011-09-29 8 views
3

누구나 MVC에서 Dynatree 플러그인을 사용한 예가 있습니까? 나는 많은 진전없이 그것에 씨름하고있다. 나는 JsonResult를 반환하는 액션 메소드를 가지고있다. (근본적인 테이블의 모든 컬럼을 선택한다. 문제가 있는지 확실하지 않다.) 그리고 initajax 호출에서이 메소드를 호출한다.Dynatree with ASP.NET MVC

너무 많은 문제가 아니라면 샘플보기 및 컨트롤러 동작 방법을 찾고 있습니다. 어떤 도움

답변

6

에 미리

덕분에 당신은 노드 예를 직렬화 객체를 생성해야합니다.

public interface ITreeItem 
{ 
} 


    /// <summary> 
    /// Tree Item Leaf. 
    /// </summary> 
    public class TreeItemLeaf :ITreeItem 
    { 
     /// <summary> 
     /// Gets the Title. 
     /// </summary> 
     public string title; 

     /// <summary> 
     /// Gets the Tooltip. 
     /// </summary> 
     public string tooltip; 

     /// <summary> 
     /// Gets the key. 
     /// </summary> 
     public string key; 

     /// <summary> 
     /// Gets the Data. 
     /// </summary> 
     public string addClass; 

     /// <summary> 
     /// Gets the Children. 
     /// </summary> 
     public IList<ITreeItem> children; 

     /// <summary> 
     /// Gets the rel attr. 
     /// </summary> 
     public string rel; 

     /// <summary> 
     /// Gets the State. 
     /// </summary> 
     public bool isFolder; 

     /// <summary> 
     /// Gets the State. 
     /// </summary> 
     public bool isLazy; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="TreeItemLeaf"/> class. 
     /// </summary> 
     public TreeItemLeaf() 
     { 
      children = new List<ITreeItem>(); 
     } 
    /// <summary> 
    /// Initializes a new instance of the <see cref="TreeItemLeaf"/> class. 
    /// </summary> 
    /// <param name="type">The type of node.</param> 
    /// <param name="id">The Id of the node.</param> 
    /// <param name="title">The Title of the node.</param> 
    /// <param name="tooltip">The Tooltip of the node.</param> 
    public TreeItemLeaf(String type, Guid id, String title, String tooltip) 
    { 
     key = id.ToString(); 
     this.title = title; 
     isFolder = false; 
     isLazy = false; 
     this.tooltip = tooltip; 
     children = new List<ITreeItem>(); 
} 

} 


    /// <summary> 
    /// Tree Item. 
    /// </summary> 
    public class TreeItem : TreeItemLeaf 
    { 
     /// <summary> 
     /// Gets the State. 
     /// </summary> 
     public new bool isFolder; 

     /// <summary> 
     /// Initializes a new instance of the <see cref="TreeItem"/> class. 
     /// </summary> 
     public TreeItem() : base() 
     { 
     } 

     /// <summary> 
     /// Initializes a new instance of the <see cref="TreeItem"/> class. 
     /// </summary> 
     /// <param name="type">The type of node.</param> 
     /// <param name="id">The Id of the node.</param> 
     /// <param name="title">The Title of the node.</param> 
     /// <param name="tooltip">The tooltip of the node.</param> 
     public TreeItem(String type, Guid id, String title, String tooltip) : base(type, id, title, tooltip) 
     { 
      isFolder = true; 
      isLazy = true; 
     } 

    } 

이가 있으면, 당신은 당신이 Dynatee 데모 http://wwwendt.de/tech/dynatree/doc/samples.html에 가면 당신이 당신의 결과에서 구축 필요합니다 Json(IList<ITreeItem>) ..

, 당신은 공부 파이어 폭스/방화범을 사용할 수 있습니다 반환 할 수 있습니다 HTTP 요청은 전달되는 내용과 리턴 된 내용을 정확하게 확인합니다.

 // --- Initialize first Dynatree ------------------------------------------- 
     $("#tree").dynatree({ 
      fx: { height: "toggle", duration: 500 }, 
      selectMode: 1, 
      clickFolderMode: 1, 
      children : @Html.Raw(String.Format("{0}", ViewData["tree"]).Replace("\"children\":[],", "")), 
      onLazyRead: function (node) { 
       node.appendAjax({ 
        url: "@Url.Action("treedata", "tree")", 
        type: "GET", 
        data: { "id": node.data.key, // Optional url arguments 
         "mode": "all" 
        }, 
        error: function(node, XMLHttpRequest, textStatus, errorThrown) { 

           } 
        } 
       }); 
      }, //.... cut short for brevity 

나는에 초기 트리 상태를 embeding하고있다 "아이들 :"일부를 다음과 같이보기에

내 나무입니다. Ajax 독서는 "onLazyRead :"부분에 설정되어 있습니다.

내 Ajax 호출은 다음과 같습니다

public JsonResult TreeData(FormCollection form) 
    { 
     return GetTreeData(Request.QueryString["id"], Request.QueryString["uitype"]); 
    } 

GetTreeData() 함수는 JSON (ITreeItem)를 반환;

파이어 폭스/파이어 버그와 그 "NET"기능을 사용하여 무엇이 돌아가고 돌아가고 있는지 확인하는 것이 좋습니다.

희망이 있습니다.

+0

빠른 답장을 보내 주셔서 감사합니다. 제안 된대로 객체를 생성하고 그 객체가 움직이는 데 도움이되는지 봅니다. – SimpleUser

+0

답장은 빠릅니다. 현재 Dynatree라는 훌륭한 jQuery 플러그인을 사용하고 매우 쉽게 구성하고 사용할 수있는 프로젝트를 진행하고 있습니다. – Steve

+0

스티브, 아직 여기서 운이별로 없어요. 내 컨트롤러 작업을 'public JsonResult GetCategories()'로 정의했으며이 작업은 이제 return Json (myTreeObj); '. 나는 이것을 initajax 호출을 통해 $ ("# tree")라고 부른다. dynatree ({ initajax : { url : '/ KBHome/GetCategories'}}); 이것은 어떤 이유로 나의 행동에 부딪치지 않는다! 내 initajax 호출에 문제가 있습니까? 다시 귀찮게해서 미안해. – SimpleUser

2

방금 ​​Dynatree를 찾았으며 MVC 프로젝트에서 사용하고 있습니다. 여기 내가 어떻게했는지 예가있다. 나는 단지 basic example처럼보기에 직접 데이터를 넣기로 결정했습니다.

내 데이터는 캘리포니아 내의 도시 목록이며 카운티별로 그룹화되어 있습니다.

내 컨트롤러는 단순히 내보기에보기 모델을 전달하고 뷰 모델은 CitiesAvailable 속성이

:

public IEnumerable<City> CitiesAvailable { get; set; } 
시 개체 내 목록 데이터베이스 (EF4)에서 잡고 실제 도시 객체는이다

다음 : 내보기에

CityObject

을 나는 카운티의 목록과 도시를 포함하는 UL를 만드는 것은 (내가 면도기를 사용하고 있지만 웹 양식 충분히 쉽게해야 알아낼) :

그것은 잘 작동

$("#tree").dynatree({ 
    checkbox: true, 
    selectMode: 3, 
    fx: { height: "toggle", duration: 200 } 
}); 

:

<div id="tree"> 
    <ul id="treedata" style="display: none;"> 
     @foreach (var county in Model.CitiesAvailable.Select(c => c.County).Distinct().OrderBy(c => c)) 
     { 
      <li data="icon: 'false'">@county 
       <ul> 
        @foreach (var city in Model.CitiesAvailable.Where(c => c.County == county).OrderBy(c => c.Name)) 
        { 
         <li data="icon: 'false'" id="@city.Id">@city.Name</li> 
        } 
       </ul> 
      </li> 
     } 
    </ul> 
</div> 

16, 그런 다음 내 자바 스크립트에서 나는 다음과 같은 사용!여기에 몇 가지 항목과 출력의 샘플을 검사입니다 :

Screenshot of Dynatree result

아무것도 이해가되지 않습니다 알려줘.

참고 : 필자는 아이콘을 원하지 않기 때문에 li 요소에서 data = "icon : 'false'"를 사용합니다.

+0

안녕하세요, 어떻게 데이터를 서버에 다시 게시 하시겠습니까? http://stackoverflow.com/questions/9692398/dynatree-asp-net-mvc-how-do-you-post-data-back-to-server – chobo2

0

당신은 단순히 JSON 문자열로 개체를 변환하고, 텍스트로 서버로 보낼 수는

이는 JS 코드 :

var dict = $("#tree").dynatree("getTree").toDict(); 
var postData = JSON.stringify(dict["children"]); 
$.ajax({ type: "POST", 
        url: "/UpdateServer/SaveUserTree", 
        data: {tree:postData}, 
        dataType: "html" 
       }); 

그리고 이것은 컨트롤러 코드 :

[HttpPost] 
    public void SaveUserTree(string tree = "") 
    { 

     HttpContext.Application["UserTree"] = tree; 

    } 

이 문자열 데이터를 클라이언트에 다시 보낼 수 있습니다.

if (HttpContext.Application["UserTree"] != null) 
      ViewBag.TreeData = new  HtmlString(HttpContext.Application["UserTree"].ToString()); 

그리고 마지막으로, 당신은이 데이터보기에, 트리를 초기 수 있습니다

var treeData= @(ViewBag.TreeData) 

$(function(){ 

    // --- Initialize sample trees 
    $("#tree").dynatree({ 
     children: treeData 
    }); 

});