This is a migrated thread and some comments may be shown as answers.

[Solved] Client side binding from ajax call with multiple arguments

1 Answer 99 Views
TreeView
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Latisha
Top achievements
Rank 1
Latisha asked on 10 Nov 2011, 09:38 PM
Hi,

Let me premise this with I'm new to asp.net, mvc, and telerik controls.
The problem: my view has several cascading comboboxes where the selected value of three of the comboboxes are used as arguments in my controller's function - this function is used to retrieve the data needed to populate the tree.  I managed to get the arguments passed to my controller via a OnChange event from a combobox.  How do I bind the result back to the tree from my javascript function?

I took a look at this thread but I wasnt sure how to follow that example, http://www.telerik.com/community/forums/aspnet-mvc/treeview/how-to-bind-the-treeview-by-ajax.aspx

Thanks in advance,
Latisha (Customer ID is: AH728462)

My partial ScriptTreeView.cshtml
@using Website.Models.Database.Automation;
@model IEnumerable<Website.Models.Database.Automation.Script>
<div id='Tree'>          
@Html.Telerik().TreeView().Name("TreeView").ShowCheckBox(true).BindTo(Model, mappings =>
{
    mappings.For<Script>(binding => binding.ItemDataBound((item, script) =>
    {
            item.Text = script.FriendlyName;                           
            item.Value = script.ID.ToString();  
    }).Children(script => script.runconfigs));
                 
    mappings.For<RunConfig>(binding => binding.ItemDataBound((item, runconfig) =>
    {
        item.Text = runconfig.Name;                           
        item.Value = runconfig.ID.ToString();                        
    }));
})   
         
<script type="text/javascript">
    $(document).ready(function () {
    $('#TreeView').find("li:has(ul)").find('> div > .t-checkbox :checkbox').bind('click', function (e) {
        var isChecked = $(e.target).is(':checked');
        var treeView = $($(e.target).closest('.t-treeview')).data('tTreeView');
        var checkboxes = $(e.target).closest('.t-item').find('> ul > li > div > .t-checkbox :checkbox');
        $.each(checkboxes, function (index, checkbox) {
            $(checkbox).attr('checked', isChecked ? true : false);
            treeView.checkboxClick(e, checkbox);
        });
        });
    })
</script>       
</div>

My javascript function
function loadScripts(e) {
           var url = '@Url.Action("_getScripts", "Home")';
           var typeCombo = $('#Type').data('tComboBox');
           var productCombo = $("#Product").data("tComboBox");
           var envCombo = $('#Environment').data('tComboBox');
           var tree = $('#TreeView').data("tTreeView");
           $.get(url, { EnvironmentID: envCombo.value(), ProductID: productCombo.value(), CategoryID: typeCombo.value() }, function (data) {
               //No idea what to put here
           });
       }


My controller
public class HomeController : Controller
    {
        private AutomationEntities context = new AutomationEntities();
        private LabManagerEntities lbcontext = new LabManagerEntities();
        public ActionResult Index()
        {
            ViewBag.Message = "Enter a New Request";
            ViewBag.Products = context.Products.ToList();
            ViewBag.Configuration = lbcontext.OS_Browser.ToList();
            return View();
        }
 
        public ActionResult About()
        {
            return View(getScripts());
        }
 
 
 public JsonResult _getScripts(int EnvironmentID, int ProductID, int CategoryID)
        {
            var scripts = (from s in context.Scripts
                           join r in context.RunConfigs on s.ID equals r.FK_RunConfigs_Scripts
                           where r.FK_RunConfigs_Environments == EnvironmentID &&
                               s.Category == CategoryID && s.FK_Scripts_Products == ProductID
                           select s).ToList();
 
//This is where I start to get lost
//I saw from some example in this forum, the code snippet below which if I understand it building the tre
//I couldnt figure out how to add children to it like I was able to do in my view
/*
            IEnumerable nodes = from item in scripts
                               select new TreeViewItemModel
                                {
                                    Text = item.FriendlyName,
                                    Value = item.ID.ToString(),
                                    LoadOnDemand = true,
                                    Enabled = true
                                };
            List<TreeViewItem> tree = new List<TreeViewItem>();
            
            foreach (Script script in scripts)
            {
                TreeViewItem node = new TreeViewItem();
                node.Text = script.FriendlyName;
                tree.Add(node);
            }
*/
            return Json(new { Data = nodes }, JsonRequestBehavior.AllowGet);
      

1 Answer, 1 is accepted

Sort by
0
Petur Subev
Telerik team
answered on 15 Nov 2011, 11:27 AM
Hello Latisha,


If I understand your scenario correctly you want to apply filter to the TreeView control collection via 3 ComboBoxes.
The main steps to accomplish this are:

  • Create a Javascript function hooked to the OnChange event of the combobox to make an ajax request
  • In the controller create an action method to handle the ajax request and filter the collection with the passed arguments
  • Create a TreeViewItem hierarchical collection from the filtered collection
  • Return the TreeViewItem collection as JsonResult
  • Bind the returned collection to the TreeView in the ajax success function

Basically you are on the right way, you just need to populate the parent collection with children in your action method handling the ajax request. You can do this like shown in the snippet below:
List<TreeViewItem> nodes = new List<TreeViewItem>();
foreach (var p in parenets)
{
    var node = new TreeViewItem
        {
            Text = p.ParentName,
            Value = p.ParentValue,
            Enabled = true
        };
    foreach (var c in p.Children)
    {
        node.Items.Add(new TreeViewItem
        {
            Text = c.ChildName,
            Value = c.ChildValue
        });
    }
    nodes.Add(node);
}
return new JsonResult { Data = nodes, JsonRequestBehavior = JsonRequestBehavior.AllowGet };


The javascript function calling ajax should be similar to this one:
function itemChange(args) {
    var filterValue1 = $("#filter1").data("tComboBox").value() ;
    
    var url ='Home/Filtered';
    $.ajax({
        url: url,
        data: { contactTitle: filterValue1 },
        contentType:"application/json",
        success: function (data) {
             var treeview = $("#TreeView").data("tTreeView");
treeview.bindTo(data);
        }
    });
}

Also I attached a project covering a simple scenario with the idea. I hope this helps.


Greetings,
Pesho
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the Telerik Extensions for ASP.MET MVC, subscribe to their blog feed now
Tags
TreeView
Asked by
Latisha
Top achievements
Rank 1
Answers by
Petur Subev
Telerik team
Share this question
or