Skip to main content Skip to footer

Tree with Knockout in a MVC application

Tree widget is used to present items in a hierarchical tree structure. It can easily be used in a MVC application as shown in our online demo. Lets discuss how you can bind WijTree with Knockout in MVC application and pass the checked nodes from View to the controller. To start, you can refer to this sample demonstrating how

    tag is converted to WijTree widget and can be bound with Knockout. But, the problem is that the tree nodes of the wijtree widget are not input elements of the form. Thereby, on submitting the form., you cannot pass the checked nodes directly. To resolve this, you can use the ‘getCheckedNodes’ method of the wijtree widget. The trick is to get the checked nodes with the help of this method and then, create hidden fields for each checked node like this:

    $(document).ready(function () {  
      //handle the click event  
      $(":submit").click(function () {  
        //get the checked nodes  
        var checkedNodes = $('#wijtree').wijtree("getCheckedNodes");  
        //traverse through the checked nodes  
        $(checkedNodes).each(function () {  
            //create hidden fields  
            $("<input>", { type: "hidden", name: "wijtreenode" })  
            //add to the form  
             .appendTo("form")  
            //set the value  
            .val($(this).wijtreenode("option", "text"));  
         });  
      })  
    });
    

    After doing so, you can get the value of hidden fields containing the checkedNodes in the controller and do the required manipulation. Here is the sample code which you can use:

    public ActionResult Submit(FormCollection formCollection)  
    {  
      if (formCollection["Save"] != null)  
        {  
          ViewData["Checked_Countries"] =  formCollection["wijtreenode"];  
          //do work here  
         }  
       return View("Index");  
    }
    

    Kindly check the attached sample implementing the same.

MESCIUS inc.

comments powered by Disqus