Kendo MVC Treeview获取所有已检查的节点并将它们传递给Controller

时间:2016-03-02 19:18:01

标签: javascript c# asp.net-mvc kendo-asp.net-mvc kendo-treeview

第一次使用MVC5和Telerik ...我正在阅读Active Directory并让所有安全组显示在TreeView中。管理员完成选择角色后,他/她将按“保存组”按钮,然后javascript应该获取所有节点并将它们传递给控制器​​。控制器将保存到数据库。我需要知道如何访问给定节点的datacontext。获得数据上下文后,我可以继续获取所有节点上下文并将其传递给控制器​​。

Kendo Treeview和按钮:

@{
    ViewBag.Title = "Configure";
}
@model IEnumerable<CMDB.Web.Models.AdminGroups>

<div>
    <input id="save" type="button" value="Save Groups" onclick="SaveData()" />
    <input id="return" type="button" value="Return" onclick="location.href='@Url.Action("Index", "Admin")'" />

    @(Html.Kendo().TreeView()
        .Name("treeview")
        .Checkboxes(checkboxes => checkboxes
            .Name("checkedFiles")
            .CheckChildren(true)
        )
        .Events(events => events.Check("onCheck"))
        .DataTextField("Name")
        .AutoScroll(true)
        .DataSource(source => source
            .Model(model => model.Id("id").HasChildren("hasChildren"))
            .Read(read => read.Action("GetActiveDircetoryGroups", "Configure"))
        )
    )
</div>

使用Javascript:

<script type="text/javascript" >
    //show checked node IDs on datasource change
    function onCheck() {
        var treeView = $("#treeview").data("kendoTreeView");
    var id = treeView.dataItem(e.node);
    }

function SaveData() {

    var AllSelectedNodes = new Array();
    AllSelectedNodes = ($("#treeview .k-item input[type=checkbox]:checked").closest(".k-item"));
    alert(AllSelectedNodes.join('\n'));
    var myApiUrl = '@Url.HttpRouteUrl("DefaultAPI", new { controller = "AdminValues", action = "SaveSelectedAdmins"})';
    var movies = $.ajax({
            url: myApiUrl,
        type: 'POST',
        data: AllSelectedNodes
    });
    }

</script>

控制器:

[HttpPost]
public void SaveSelectedAdmins(IEnumerable<CMDB.Web.Models.AdminGroups> ag)
{
    string Sids = string.Empty;
    foreach (var s in ag)
    {
        var pc = new PrincipalContext(ContextType.Domain, "", "");//blank for security purposes
        GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Guid, s.id.Value.ToString());
        if (s.id.Value.ToString() == gp.Guid.Value.ToString())
        {
            Sids = Sids + "," + gp.Sid;
        }
    }
    using (var ctx = new Data.DBContext())
    {
        var d2 = (from d in ctx.Set<Entities.Config>()
                  where d.Property == "str"
                  select d).SingleOrDefault();
        d2.Value = Sids;
        ctx.SaveChanges();
    }
}

1 个答案:

答案 0 :(得分:0)

使用$ .post而不是$ .ajax解决了这个问题。