【问题标题】:spring.net + nhibernate + jquery ajax call to webmethod at codebehindspring.net + nhibernate + jquery ajax 在代码隐藏处调用 webmethod
【发布时间】:2011-01-28 17:48:57
【问题描述】:

我正在尝试对代码隐藏文件上的静态方法进行 jquery ajax 调用。问题是 Spring 注入的 ArtistManager 不是静态的,我不能在静态 webmethod 中使用它。我正在寻找有关如何实现此功能的任何想法

ArtistList.aspx

$(document).ready(function () {
        $("#Result").click(function () {
            $.ajax({
                type: "POST",
                url: "ArtistList.aspx/GetArtists",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $("#Result").text(msg.d);
                    alert("Success: " + msg.d);
                },
                error: function (msg) {
                    // Replace the div's content with the page method's return.
                    $("#Result").text(msg.d);
                    alert("Error: " + msg.d);
                }
            });
        });
    });

ArtistList.aspx.cs

    private IArtistManager artistManager;
    public IArtistManager ArtistManager
    {
        set { this.artistManager = value; }
        get { return artistManager; }
    }
    protected long rowCount = 0;
.
.
.

    [WebMethod]
    public static IList<App.Data.BusinessObjects.Artist> GetArtists()
    {
        //return ArtistManager.GetAll("Name", "ASC", 1, 100, out rowCount);
    }

【问题讨论】:

  • 为什么 GetArtists() 是一个静态方法?
  • 知道了 - 需要静态才能允许 ASP.NET AJAX 回调到 ASPX 页面中的 Web 方法,请阅读 here
  • SO上有一个类似的问题:stackoverflow.com/questions/2133194/…

标签: asp.net jquery ajax nhibernate spring.net


【解决方案1】:

假设有一个单独的上下文,其中配置了一个名为 artistManager 的 IArtistManager

using Spring.Context.Support;
// ...
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
  IApplicationContext context = ContextRegistry.GetContext(); // get the application context
  IArtistManager mngr = (IArtistManager)context.GetObject("artistManager"); // get the object
  return mngr.GetAll("Name", "ASC", 1, 100, out rowCount);
}

请注意,此代码也不会编译,因为rowCount 是实例成员,类似于您问题中的artistManager

【讨论】:

  • Marijn的做法是正确的,将rowcount作为参数传入getartists函数。同时将行数和艺术家列表传递给客户端等。
  • 感谢 Marijn,我尝试了您的解决方案,效果很好:) 但是我最终将我的要求实现为 Web 服务。
【解决方案2】:

不知道spring,但我相信它有类似结构图的东西。

ObjectFactory.GetInstance<IAristManager>.GetAll();

【讨论】:

    猜你喜欢
    • 2020-02-11
    • 2013-08-16
    • 2018-07-30
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多