Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.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
Javascript Jquery上下文菜单ajax获取菜单项_Javascript_Jquery_Asp.net Mvc 4_Contextmenu - Fatal编程技术网

Javascript Jquery上下文菜单ajax获取菜单项

Javascript Jquery上下文菜单ajax获取菜单项,javascript,jquery,asp.net-mvc-4,contextmenu,Javascript,Jquery,Asp.net Mvc 4,Contextmenu,我的登录页上有一个jquery上下文菜单,其中有硬代码菜单项。现在我想从服务器获取菜单项。其基本思想是在上下文菜单列表中的指定目录中显示文件名,并在用户单击该文件时打开该文件 到目前为止我已经做到了 ***更新*** C#代码 [HttpPost] public JsonResult GetHelpFiles() { List<Manuals> manuals = null; var filesPat

我的登录页上有一个jquery上下文菜单,其中有硬代码菜单项。现在我想从服务器获取菜单项。其基本思想是在上下文菜单列表中的指定目录中显示文件名,并在用户单击该文件时打开该文件

到目前为止我已经做到了

***更新***

C#代码

[HttpPost]
        public JsonResult GetHelpFiles()
         {
            List<Manuals> manuals = null;

            var filesPath = Server.MapPath(@"\HelpManuals");

            var standardPath = new DirectoryInfo(filesPath);

            if (standardPath.GetFiles().Any())
            {
               manuals = standardPath.GetFiles().Select(x => new Manuals
               {
                    Name = GetFileNamewithoutExtension(x.Name),
                    Path = x.Name
                }).ToList();
            }

            return Json(manuals, JsonRequestBehavior.AllowGet);
        }

        private string GetFileNamewithoutExtension(string filename)
        {
            var extension = Path.GetExtension(filename);

           return filename.Substring(0, filename.Length - extension.Length);
        }
$.post("/Home/GetHelpFiles", function (data) {
    $.contextMenu({
        selector: '#helpIcon',
        trigger: 'hover',
        delay: 300,
        build: function($trigger, e) {
            var options = {
                callback: function(key) {
                    window.open("/HelpManuals/" + key);
                },
                items: {}
            };
            $.each(data, function (item, index) {
                console.log("display name:" + index.Name);
                console.log("File Path:" + index.Path);
                options.items[item.Value] = {
                    name: index.Name,
                    key: index.Path
                }
            });
        }
    });
});
$.post("/Home/GetHelpFiles", function (data) {
                $.each(data, function (index, item) {
                    var e = '<command label="' + item.Name + '" id ="' + item.Path + '"></command>';
                    $("#html5menu").append(e);
                });


                $.contextMenu({
                    selector: '#helpIcon',
                    trigger: 'hover',
                    delay: 300,
                    items: $.contextMenu.fromMenu($('#html5menu'))
                });
            });


 $("#dynamicMenu").on("click", "menu command", function () {
        var link = $(this).attr('id');
        window.open("/HelpManuals/" + link);
    });

多亏了马特。现在,build函数在hover上启动。。但是我被非法调用。。。当迭代json结果时,index.Name和this.Name给出正确的结果。但是item.Name没有给出任何信息。

要动态地将项目添加到上下文菜单中,您需要进行一些更改

$.contextMenu({
    selector: '#helpIcon',
    trigger: 'hover',
    delay: 300,
    build: function($trigger, e){
        var options = {
            callback: function (key) {
                var manual;
                if (key == "adminComp") {
                    manual = "AdminCompanion.pdf";
                } else {
                    manual = "TeacherCompanion.pdf";
                }
                window.open("/HelpManuals/" + manual);
            },
            items: {}
        }

        //how to populate from model
        @foreach(var temp in Model.FileList){
            <text> 
                options.items[temp.Value] = {
                    name: temp.Name,
                    icon: 'open'
                }
            </text>
        }

        //should be able to do an ajax call here but I believe this will be called 
        //every time the context is triggered which may cause performance issues
        $.ajax({
            url: '@Url.Action("Action", "Controller")',
            type: 'get',
            cache: false,
            async: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (_result) {
            if (_result.Success) {
                $.each(_result, function(item, index){
                    options.items[item.Value] = {
                        name: item.Name,
                        icon: 'open'
                    }
                });
            }
        });
        return options;
    }

});
$.contextMenu({
选择器:“#帮助图标”,
触发器:“悬停”,
延误:300,
构建:函数($trigger,e){
变量选项={
回调:函数(键){
风险值手册;
如果(键==“adminComp”){
manual=“admincompany.pdf”;
}否则{
manual=“TeacherCompanion.pdf”;
}
打开(“/HelpManuals/”+手动);
},
项目:{}
}
//如何从模型中填充
@foreach(Model.FileList中的var temp){
选项.项目[温度值]={
姓名:临时姓名,
图标:“打开”
}
}
//应该能够在这里调用ajax,但我相信它会被调用
//每次触发可能导致性能问题的上下文时
$.ajax({
url:'@url.Action(“Action”,“Controller”)',
键入:“get”,
cache:false,
async:true,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:函数(_结果){
如果(_result.Success){
$.each(_结果、函数(项、索引){
选项.items[item.Value]={
名称:item.name,
图标:“打开”
}
});
}
});
返回选项;
}
});

因此,您可以使用build和其中的define选项,并将回调放在其中。其中定义的项是空的,并在构建中动态填充。我们根据通过模型传递的内容构建列表,但我相信您可以像上面所示的那样将ajax调用放在构建中。希望这将使您获得正确的跟踪至少是k。

在彻底阅读jquery上下文菜单文档之后,我终于找到了更好的解决方案

C#代码

 public JsonResult GetHelpFiles()
         {
            List<Manuals> manuals = null;

            var filesPath = Server.MapPath(@"\HelpManuals");

            var standardPath = new DirectoryInfo(filesPath);

            if (standardPath.GetFiles().Any())
            {
               manuals = standardPath.GetFiles().Select(x => new Manuals
               {
                    Name = GetFileNamewithoutExtension(x.Name),
                    Path = x.Name
                }).ToList();
            }

            return Json(manuals, JsonRequestBehavior.AllowGet);
        } 
publicjsonresult GetHelpFiles()
{
列表手册=空;
var filesPath=Server.MapPath(@“\HelpManuals”);
var standardPath=新目录信息(filepath);
if(standardPath.GetFiles().Any())
{
manuals=standardPath.GetFiles()。选择(x=>newmanuals
{
Name=GetFileNamewithoutExtension(x.Name),
Path=x.Name
}).ToList();
}
返回Json(manuals,JsonRequestBehavior.AllowGet);
} 
HTML5

<div id="dynamicMenu">
                        <menu id="html5menu" type="context" style="display: none"></menu>
                    </div> 

JavaScript代码

[HttpPost]
        public JsonResult GetHelpFiles()
         {
            List<Manuals> manuals = null;

            var filesPath = Server.MapPath(@"\HelpManuals");

            var standardPath = new DirectoryInfo(filesPath);

            if (standardPath.GetFiles().Any())
            {
               manuals = standardPath.GetFiles().Select(x => new Manuals
               {
                    Name = GetFileNamewithoutExtension(x.Name),
                    Path = x.Name
                }).ToList();
            }

            return Json(manuals, JsonRequestBehavior.AllowGet);
        }

        private string GetFileNamewithoutExtension(string filename)
        {
            var extension = Path.GetExtension(filename);

           return filename.Substring(0, filename.Length - extension.Length);
        }
$.post("/Home/GetHelpFiles", function (data) {
    $.contextMenu({
        selector: '#helpIcon',
        trigger: 'hover',
        delay: 300,
        build: function($trigger, e) {
            var options = {
                callback: function(key) {
                    window.open("/HelpManuals/" + key);
                },
                items: {}
            };
            $.each(data, function (item, index) {
                console.log("display name:" + index.Name);
                console.log("File Path:" + index.Path);
                options.items[item.Value] = {
                    name: index.Name,
                    key: index.Path
                }
            });
        }
    });
});
$.post("/Home/GetHelpFiles", function (data) {
                $.each(data, function (index, item) {
                    var e = '<command label="' + item.Name + '" id ="' + item.Path + '"></command>';
                    $("#html5menu").append(e);
                });


                $.contextMenu({
                    selector: '#helpIcon',
                    trigger: 'hover',
                    delay: 300,
                    items: $.contextMenu.fromMenu($('#html5menu'))
                });
            });


 $("#dynamicMenu").on("click", "menu command", function () {
        var link = $(this).attr('id');
        window.open("/HelpManuals/" + link);
    });
$.post(“/Home/GetHelpFiles”,函数(数据){
$。每个(数据、功能(索引、项目){
变量e=“”;
$(“#HTML5菜单”)。附加(e);
});
$.contextMenu({
选择器:“#帮助图标”,
触发器:“悬停”,
延误:300,
项目:$.contextMenu.fromMenu($('#html5menu'))
});
});
$(“#动态菜单”)。在(“单击”、“菜单命令”上,函数(){
var link=$(this.attr('id');
打开(“/HelpManuals/”+链接);
});

我用以下方法解决了这个问题

在用户触发的右键单击上,我在构建函数中返回false。这将阻止上下文菜单打开。我不会操作上下文菜单,而是启动对服务器的ajax调用以获取上下文菜单项

当ajax调用成功完成时,我创建项目并将项目保存在$trigger的数据属性中。 在数据属性中保存菜单项后,我手动打开关联菜单

当构建函数再次执行时,我从数据属性中获取项目

$.contextMenu({
    build: function ($trigger, e)
    {
        // check if the menu-items have been saved in the previous call
        if ($trigger.data("contextMenuItems") != null)
        {
            // get options from $trigger
            var options = $trigger.data("contextMenuItems");

            // clear $trigger.data("contextMenuItems"),
            // so that menuitems are gotten next time user does a rightclick 
            // from the server again.
            $trigger.data("contextMenuItems", null);
            return options;
        }
        else
        {
            var options = {
                callback: function (key)
                {
                    alert(key);
                },
                items: {}
            };
            $.ajax({
                url: "GetMenuItemsFromServer",
                success: function (response, status, xhr)
                {
                    // for each menu-item returned from the server
                    for (var i = 0; i < response.length; i++)
                    {
                        var ri = response[i];
                        // save the menu-item from the server in the options.items object
                        options.items[ri.id] = ri;
                    }
                    // save the options on the table-row;
                    $trigger.data("contextMenuItems", options);

                    // open the context-menu (reopen)
                    $trigger.contextMenu();
                },
                error: function (response, status, xhr)
                {
                    if (xhr instanceof Error)
                    {
                        alert(xhr);
                    }
                    else
                    {
                        alert($($.parseHTML(response.responseText)).find("h2").text());
                    }
                }
            });
            // This return false here is important                
            return false;
        }
   });
$.contextMenu({
构建:函数($trigger,e)
{
//检查上一次通话中是否保存了菜单项
if($trigger.data(“contextMenuItems”)!=null)
{
//从$trigger获取选项
var options=$trigger.data(“contextMenuItems”);
//清除$trigger.data(“contextMenuItems”),
//这样,下次用户右键单击时将获得菜单项
//再次从服务器上删除。
$trigger.data(“contextMenuItems”,null);
返回选项;
}
其他的
{
变量选项={
回调:函数(键)
{
警报(键);
},
项目:{}
};
$.ajax({
url:“GetMenuItemsFromServer”,
成功:功能(响应、状态、xhr)
{
//对于从服务器返回的每个菜单项
对于(变量i=0;i