Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何在单击按钮时保存jstree?_Jquery_Entity Framework_Asp.net Mvc 4_Jstree - Fatal编程技术网

Jquery 如何在单击按钮时保存jstree?

Jquery 如何在单击按钮时保存jstree?,jquery,entity-framework,asp.net-mvc-4,jstree,Jquery,Entity Framework,Asp.net Mvc 4,Jstree,我第一次在asp.NETMVC4中使用jstree,首先是实体框架6.1代码 我的表i数据库为类别 CategoryId Name CreatedDate ParentId 1 category 2014-05-06 19:00:20.107 0 2 Category1 2014-05-06 19:00:20.107 1 3 Categor

我第一次在asp.NETMVC4中使用jstree,首先是实体框架6.1代码

我的表i数据库为
类别

CategoryId        Name         CreatedDate          ParentId
1               category    2014-05-06 19:00:20.107     0
2               Category1   2014-05-06 19:00:20.107     1
3               Category2   2014-05-06 19:00:20.107     1
我正在将我的jstree与此表绑定为

我的分类控制器代码是

 public JsonResult GetList(int id = 0)
        {
            var objList = GetTreeVeiwList();
           return Json(objList, JsonRequestBehavior.AllowGet);
        }
公共列表GetTreeVeilList() {

        var rootNode = (from e1 in _CategoriesBusiness.Select()
                        where e1.ParentId == 0
                        select new TreeViewNodeVM()
                        {
                            id =Convert.ToString(e1.CategoryId),
                            text = e1.Name
                        }).ToList();
        BuildChildNode(rootNode);

        return rootNode;
    }

    public JsonResult SaveChanges(string ar)
    {
        var data = new JavaScriptSerializer().Deserialize<string[]>(ar);
        Categories objCategories=null;
        foreach (var a in data)
        {
            var ab = a.Split(' ');
             objCategories=new Categories();
             int tempCategoryId;
             if (int.TryParse(ab[1], out tempCategoryId))
             {
                 objCategories.CategoryId = tempCategoryId;

                 var objcat=(from cat in _CategoriesBusiness.Select() where cat.CategoryId==tempCategoryId select cat).FirstOrDefault();
                 if (objcat != null)
                 {
                     objcat.Name = ab[0].Trim();
                     int tempParantId;
                     if (int.TryParse(ab[2], out tempParantId))
                     {
                         objcat.ParentId = tempParantId;
                     }
                     _CategoriesBusiness.Update(objcat);
                 }
                 else
                 {
                     objCategories.CategoryId = Convert.ToInt32(ab[1]);
                     objCategories.Name = ab[0];
                     int tempParantId1;
                     if (int.TryParse(ab[2], out tempParantId1))
                     {
                         objCategories.ParentId = tempParantId1;
                     }
                     _CategoriesBusiness.Create(objCategories);
                 }

             }
             else
             {
                 objCategories.Name = ab[0];
                 int tempParantId1;
                 if (int.TryParse(ab[2], out tempParantId1))
                 {
                     objCategories.ParentId = tempParantId1;
                 }
                 _CategoriesBusiness.Create(objCategories);

             }
                        }

        return Json(new { },JsonRequestBehavior.AllowGet);
    }

    private void BuildChildNode(List<TreeViewNodeVM> ListrootNode)
    {
        foreach (TreeViewNodeVM rootNode in ListrootNode)
        {
            if (rootNode != null)
            {
                List<TreeViewNodeVM> chidNode = (from e1 in _CategoriesBusiness.Select()
                                                 where e1.ParentId.ToString() == rootNode.id
                                                 select new TreeViewNodeVM()
                                                 {
                                                     id = Convert.ToString(e1.CategoryId),
                                                     text = e1.Name
                                                 }).ToList<TreeViewNodeVM>();
                if (chidNode.Count > 0)
                {
                    BuildChildNode(chidNode);
                    foreach (var childRootNode in chidNode)
                    {
                        rootNode.children.Add(childRootNode);
                    }

                }
            }
        }
    } 
var rootNode=(来自_CategoriesBusiness.Select()中的e1)
其中e1.ParentId==0
选择新的TreeViewNodeVM()
{
id=转换为字符串(e1.类别id),
text=e1.Name
}).ToList();
BuildChildNode(rootNode);
返回根节点;
}
公共JsonResult保存更改(字符串ar)
{
var data=new JavaScriptSerializer()。反序列化(ar);
类别objCategories=null;
foreach(数据中的var a)
{
var ab=a.分割(“”);
objCategories=新类别();
int tempCategoryId;
if(int.TryParse(ab[1],out tempCategoryId))
{
objCategories.CategoryId=临时类别;
var objcat=(来自_CategoriesBusiness.Select()中的cat,其中cat.CategoryId==tempCategoryId Select cat).FirstOrDefault();
if(objcat!=null)
{
objcat.Name=ab[0].Trim();
int TEMPPANTID;
if(内锥虫(ab[2],外锥虫))
{
objcat.ParentId=tempParantId;
}
_CategoriesBusiness.Update(objcat);
}
其他的
{
objCategories.CategoryId=Convert.ToInt32(ab[1]);
objCategories.Name=ab[0];
int-TEMP1;
if(内锥虫(ab[2],外锥虫1))
{
objCategories.ParentId=tempParantId 1;
}
_创建(objCategories);
}
}
其他的
{
objCategories.Name=ab[0];
int-TEMP1;
if(内锥虫(ab[2],外锥虫1))
{
objCategories.ParentId=tempParantId 1;
}
_创建(objCategories);
}
}
返回Json(new{},JsonRequestBehavior.AllowGet);
}
私有void BuildChildNode(列表ListrootNode)
{
foreach(ListrootNode中的TreeViewNodeVM根节点)
{
if(rootNode!=null)
{
列出chidNode=(来自_CategoriesBusiness.Select()中的e1)
其中e1.ParentId.ToString()==rootNode.id
选择新的TreeViewNodeVM()
{
id=转换为字符串(e1.类别id),
text=e1.Name
}).ToList();
如果(chidNode.Count>0)
{
BuildChildNode(chidNode);
foreach(chidNode中的var childRootNode)
{
rootNode.children.Add(childRootNode);
}
}
}
}
} 
这一观点是:

@*@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}*@


<link href="../../Content/dist/themes/default/style.min.css" rel="stylesheet" />
<script src="../../Content/dist/libs/jquery.js"></script>
<script src="../../Content/dist/jstree.js"></script>
@*<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.6/jquery.min.js" type="text/javascript"></script>*@

<script type='text/javascript' src="http://static.jstree.com/v.1.0pre/jquery.hotkeys.js"></script>


@model List<Web.ViewModels.TreeModels.TreeViewNodeVM>
@{

    ViewBag.Title = "Index";
}
<h2>
    Categories</h2>

<input type="button" id="btnaddFolder" value="Add new folder" onclick="File_Folder()" />
<input type="button" id="btnaddCat" value="Add new Category" onclick="File_create()" />
<input type="button" id="btnSave" value="Save Changes" onclick="SaveChanges()" />
<input type="button" id="btnCancel" value="Cancel" />

<div id="jstree">

</div> 

  <script>


      function SaveChanges() {
          debugger
          var ar = [];
          var i = 0;
          var arr = "";
          $('#jstree li').each(function () {
              debugger

              var id = $(this).attr('id');
              var text = $(this).find("a:first").text();              

              if ($(this).parent('ul.jstree-children')) {
                  var parent = $(this).parent('ul.jstree-children').parent('li').attr('id');
                  alert(text + " " + id + " " + parent);

                  var item = text + " " + id + " " + parent;
                  ar.push(item);

                  i++;
              }

          });
          arr = JSON.stringify(ar);
          //$('#jstree li.jstree-node').each(function () {

          //    some.push($(this).attr("id"));
          //    // or
          //    //some.push(this.id);
          //});
          debugger;
          $.ajax({
              type: 'post',
              url: "/Category/SaveChanges", data: { ar: arr }, success: function (result) {
                  $("#div1").html(result);
              }
          });

      }

      function AddNewNode()
      {
          File_create();
      }



      $(function () {
          // 6 create an instance when the DOM is ready
          debugger

          $("#jstree").jstree({

              "core": {


                  "animation": 0,
                  "check_callback": true,
                  "themes": { "stripes": true },
                  'data': {

                      'url': function (node) {

                          debugger
                          return node.id === '#' ?
                            '/Category/GetList' : '/Category/GetList1';
                      },
                      'data': function (node) {
                          debugger
                          return { 'id': node.id };
                      }
                  }
              },



              "contextmenu": {
                  "items": function ($node) {
                      var tree = $("#jstree").jstree(true);
                      return {
                          "Create": {
                              //"separator_before": false,
                              //"separator_after": false,
                              "label": "Create",
                              "action": function (data) {
                                  debugger;
                                      File_create();
                                  //var ref = $('#jstree').jstree(true);
                                  //ref.create_node(data);
                              }
                          },
                          "Rename": {
                              "separator_before": false,
                              "separator_after": false,
                              "label": "Rename",
                              "action": function (obj) {
                                  debugger;
                                  tree.edit($node);
                              }
                          },
                          "Remove": {
                              "separator_before": false,
                              "separator_after": false,
                              "label": "Remove",
                              "action": function (obj) {
                                  tree.delete_node($node);
                              }
                          }
                      };
                  }
              },




              "types": {
                  "#": {
                      "max_children": 1,
                      "max_depth": 4,
                      "valid_children": ["root"]
                  },
                  "root": {
                      "icon": "/static/3.0.0/assets/images/tree_icon.png",
                      "valid_children": [],
                      "name":"Folder"
                  },
                  "default": {

                      "valid_children": ["default", "file"]
                  },
                  "file": {
                      "icon": "glyphicon glyphicon-file",
                      "valid_children": []
                  }
              },
              "plugins": [
                "contextmenu", "dnd", "search",
                "state", "types", "wholerow"
              ]


          })


      });


      function File_Folder() {


          debugger
          var ref = $('#jstree').jstree(true),
              sel = ref.get_selected();
          if (!sel.length) { return false; }
          var number = 1 + Math.floor(Math.random() * 10);


          sel = ref.create_node(sel, { "type": "default"});
          if (sel) {
              ref.edit(sel);
          }
      }


      function File_create() {
          debugger
          var ref = $('#jstree').jstree(true),
              sel = ref.get_selected();
          if (!sel.length) { return false; }         

          sel = ref.create_node(sel, { "type": "file"});
          if (sel) {
              ref.edit(sel);
          }
      }
  </script>
@*@{
ViewBag.Title=“Index”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}*@
@**@
@模型列表
@{
ViewBag.Title=“Index”;
}
类别
函数SaveChanges(){
调试器
var-ar=[];
var i=0;
var arr=“”;
$('#jstree li')。每个(函数(){
调试器
var id=$(this.attr('id');
var text=$(this.find(“a:first”).text();
if($(this.parent('ul.jstree children')){
var parent=$(this.parent('ul.jstree children').parent('li').attr('id');
警报(文本+“”+id+“”+parent);
var item=text+“”+id+“”+parent;
ar.push(项目);
i++;
}
});
arr=JSON.stringify(ar);
//$('#jstree li.jstree节点')。每个(函数(){
//some.push($(this.attr(“id”));
////或
////some.push(this.id);
//});
调试器;
$.ajax({
键入:“post”,
url:“/Category/SaveChanges”,数据:{ar:arr},成功:函数(结果){
$(“#div1”).html(结果);
}
});
}
函数AddNewNode()
{
文件创建();
}
$(函数(){
//6在DOM就绪时创建一个实例
调试器
$(“#jstree”).jstree({
“核心”:{
“动画”:0,
“check_callback”:true,
“主题”:{“条纹”:真的},
“数据”:{
“url”:函数(节点){
调试器
return node.id=='#'?
“/Category/GetList”:“/Category/GetList1”;
},
“数据”:函数(节点){
调试器
返回{'id':node.id};
}
}
},
“上下文菜单”:{
“项目”:功能($node){
var-tree=$(“#jstree”).jstree(true);
返回{
“创建”:{
//“之前的分隔符”:false,
   $(document).ready(function () {
    var maxId = LastCategoryId();
    jQuery('#dialog').dialog(
        {
            'autoOpen': false,
            title: 'Info',
            buttons: {
                Ok: function () {
                    $(this).dialog("close");
                }
            }
        });

    $('#categoriesWrapperId')
        .jstree(
        {
            plugins: ["contextmenu", "dnd", "themes"],
            'core': {
                'check_callback': true,
                "themes": {
                    "name": "default"
                }
            }

        });

    $('#categoriesWrapperId').on('ready.jstree', function () {
        $("#categoriesWrapperId").jstree("open_all");
    });

    $("#saveButton").on("click", function () {
        var categoriesArray = new Array();
        var i = 0;
        $('#categoriesWrapperId li').each(function () {

            var id = $(this).attr('id').toString();
            if (id.indexOf("j") >= 0) {
                id = maxId + 1;
                $(this).attr('id', id);
                maxId = maxId + 1;
            }

            var text = $(this).find("a:first").text().trim();

            if ($(this).parent('ul.jstree-children')) {
                var parentId = $(this).parent('ul.jstree-children').parent('li').attr('id');
                var category = { id: id, name: text, parentId: parentId, createdDate: Date.now }

                categoriesArray.push(category);

                i++;
            }
        });

        $.ajax({
            type: 'post',
            url: "/Categories/Save",
            data: { categoriesArray: categoriesArray },
            success: function (response) {
                jQuery('#dialog').text(response.Message).dialog('open');
                maxId = response.LastCategoryId;
            }
        });
    });
});

function LastCategoryId() {
    var idsArray = [];
    var i = 0;
    $('#categoriesWrapperId li').each(function () {
        var id = $(this).attr('id').toString();
        idsArray.push(id);
        i++;
    });
    return Math.max.apply(Math, idsArray);
}