Javascript 上下文菜单到 C#

发布于 2024-12-19 22:40:55 字数 2361 浏览 1 评论 0原文

我使用 Jquery 创建了一个 javascript 上下文菜单,效果非常好。但有两种选择。第一个是在 C# 中创建此上下文菜单(如果可能的话)。第二种方法是在单击菜单中的按钮时运行 C# 函数。哪个选项最好?我该如何开始?亲切的问候

Javascript:

function Menu($div){
    var that = this, 
        ts = null;

    this.$div = $div;
    this.items = [];

    // create an item using a new closure 
    this.create = function(item){
      var $item = $('<div class="item '+item.cl+'">'+item.label+'</div>');
      $item
        // bind click on item
        .click(function(){
          if (typeof(item.fnc) === 'function'){
            item.fnc.apply($(this), []);
          }
        })
        // manage mouse over coloration
        .hover(
          function(){$(this).addClass('hover');},
          function(){$(this).removeClass('hover');}
        );
      return $item;
    };
    this.clearTs = function(){
      if (ts){
        clearTimeout(ts);
        ts = null;
      }
    };
    this.initTs = function(t){
      ts = setTimeout(function(){that.close()}, t);
    };
  }

  // add item
  Menu.prototype.add = function(label, cl, fnc){
    this.items.push({
      label:label,
      fnc:fnc,
      cl:cl
    });
  }

  // close previous and open a new menu 
  Menu.prototype.open = function(event){
    this.close();
    var k,
        that = this,
        offset = {
          x:0, 
          y:0
        },
        $menu = $('<div id="menu"></div>');

    // add items in menu
    for(k in this.items){
      $menu.append(this.create(this.items[k]));
    }

    // manage auto-close menu on mouse hover / out
    $menu.hover(
      function(){that.clearTs();},
      function(){that.initTs(3000);}
    );

    // change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
    if ( event.pixel.y + $menu.height() > this.$div.height()){
      offset.y = -$menu.height();
    }
    if ( event.pixel.x + $menu.width() > this.$div.width()){
      offset.x = -$menu.width();
    }

    // use menu as overlay
    this.$div.gmap3({
      action:'addOverlay',
      latLng: event.latLng,
      content: $menu,
      offset: offset
    });

    // start auto-close
    this.initTs(5000);
  }

  // close the menu
  Menu.prototype.close = function(){
    this.clearTs();
    this.$div.gmap3({action:'clear', name:'overlay'});
  }

I have created a javascript context menu using Jquery that works perfectly. But there are two options. The first one is to create this context menu in C# (If that's possible). The second way is to run a C# Function when a button in the menu is clicked. Which option is the best and how do i start? Kind regards

Javascript:

function Menu($div){
    var that = this, 
        ts = null;

    this.$div = $div;
    this.items = [];

    // create an item using a new closure 
    this.create = function(item){
      var $item = $('<div class="item '+item.cl+'">'+item.label+'</div>');
      $item
        // bind click on item
        .click(function(){
          if (typeof(item.fnc) === 'function'){
            item.fnc.apply($(this), []);
          }
        })
        // manage mouse over coloration
        .hover(
          function(){$(this).addClass('hover');},
          function(){$(this).removeClass('hover');}
        );
      return $item;
    };
    this.clearTs = function(){
      if (ts){
        clearTimeout(ts);
        ts = null;
      }
    };
    this.initTs = function(t){
      ts = setTimeout(function(){that.close()}, t);
    };
  }

  // add item
  Menu.prototype.add = function(label, cl, fnc){
    this.items.push({
      label:label,
      fnc:fnc,
      cl:cl
    });
  }

  // close previous and open a new menu 
  Menu.prototype.open = function(event){
    this.close();
    var k,
        that = this,
        offset = {
          x:0, 
          y:0
        },
        $menu = $('<div id="menu"></div>');

    // add items in menu
    for(k in this.items){
      $menu.append(this.create(this.items[k]));
    }

    // manage auto-close menu on mouse hover / out
    $menu.hover(
      function(){that.clearTs();},
      function(){that.initTs(3000);}
    );

    // change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
    if ( event.pixel.y + $menu.height() > this.$div.height()){
      offset.y = -$menu.height();
    }
    if ( event.pixel.x + $menu.width() > this.$div.width()){
      offset.x = -$menu.width();
    }

    // use menu as overlay
    this.$div.gmap3({
      action:'addOverlay',
      latLng: event.latLng,
      content: $menu,
      offset: offset
    });

    // start auto-close
    this.initTs(5000);
  }

  // close the menu
  Menu.prototype.close = function(){
    this.clearTs();
    this.$div.gmap3({action:'clear', name:'overlay'});
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

计㈡愣 2024-12-26 22:40:55

好吧,您可以在 C# 中创建一个服务器控件并从中发出菜单,但由于您已经有了一个工作菜单,因此调用服务器端方法来响应单击会更容易。如果您使用 jQuery,则非常简单:

$.ajax({
    url: "/Path/To/MyMethod",
    type: "POST",
    dataType: "JSON",
    data: <some POST data>,
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        // Do your stuff here
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // Report error
    }
});

服务器端部分的实现可以是 ASPX 页面中的静态 [WebMethod],或者如果您使用 MVC,则它可以是对控制器方法的直接调用。

Well you could create a server control in C# and emit the menu from it, but since you already have a working menu it's just easier to call a server-side method in response to a click. If you're using jQuery it's as easy as:

$.ajax({
    url: "/Path/To/MyMethod",
    type: "POST",
    dataType: "JSON",
    data: <some POST data>,
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        // Do your stuff here
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // Report error
    }
});

The implementation of the server-side part can be either a static [WebMethod] in an ASPX page, or if you're using MVC then it can be a direct call to a controller method.

挖个坑埋了你 2024-12-26 22:40:55

我假设您想要做的是在选择上下文菜单上的项目时调用 ac# 方法。如果您使用 MVC 模型,这很容易做到。使用如下调用,以 JSON 格式传递参数。我只是使用我的代码中的骨架方法作为示例,当您单击上下文菜单链接时,您将调用 LibraryRead 方法

 Client Side

 function LibraryRead() {   
    $.ajax({
        url : 'Library/ReadLibrary',
        type : "POST",
        data : JSON.stringify(idLibrary),
        dataType : "json",
        contentType : "application/json; charset=utf-8",
        success : function(result) {
            $(result).each(function() {
                ....Process Results
            });
        },
        error : function() {
            .....If something goes wrong, if you use a try catch in your code 
            which does not handle the exception correctly and something goes wrong 
            this will not be triggered. Use propper exception handling.
        }
    });
}



Server Side 

// Post: /Library/ReadLibrary
[HttpPost]
public JsonResult ReadLibrary(int idLibrary)
{
    try
    {

        var library = READ your library here from your data source

        return this.Json(library);
        }
        else
        {
            return null;
        }
    }
    catch (Exception ex)
    {
        //Exception handling omitted for simplicity
    }
}

在 google 上搜索 MVC3 和 JQuery / Javascript 使用 JSON 的调用,有大量可用资源。

如果您不使用 MVC 模式,您也许可以在后面的代码中使用 Web 服务或方法。您需要在方法上添加适当的属性,例如 [Ajax.AjaxMethod()] 或 [WebMethod]

I am assuming what you are trying to do is call a c# method when an Item on the context menu is selected. If you are using an MVC model this is pretty easy to do. Use a call as follows passing the parameters in JSON format. I am just using a skeleton method from my code as an example you would call LibraryRead method when you click on the Context Menu Link

 Client Side

 function LibraryRead() {   
    $.ajax({
        url : 'Library/ReadLibrary',
        type : "POST",
        data : JSON.stringify(idLibrary),
        dataType : "json",
        contentType : "application/json; charset=utf-8",
        success : function(result) {
            $(result).each(function() {
                ....Process Results
            });
        },
        error : function() {
            .....If something goes wrong, if you use a try catch in your code 
            which does not handle the exception correctly and something goes wrong 
            this will not be triggered. Use propper exception handling.
        }
    });
}



Server Side 

// Post: /Library/ReadLibrary
[HttpPost]
public JsonResult ReadLibrary(int idLibrary)
{
    try
    {

        var library = READ your library here from your data source

        return this.Json(library);
        }
        else
        {
            return null;
        }
    }
    catch (Exception ex)
    {
        //Exception handling omitted for simplicity
    }
}

Do a search on google for MVC3 and JQuery / Javascript calls with JSON, there are loads of resources available.

If you are not using MVC pattern you may be able to use a web service or method in the code behind. You need to add the appropriate attribute over the method though like [Ajax.AjaxMethod()] or [WebMethod]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文