【问题标题】:Can you retrieve a user control from a static method from page?您可以从页面的静态方法中检索用户控件吗?
【发布时间】:2013-05-11 16:57:51
【问题描述】:

我正在尝试使用 ajax/jquery 从客户端调用用户控件中的方法。我的 ajax 看起来像这样:

function starClick(starIndex) {
    $.ajax({
        type: "POST",
        url: "ItemPage.aspx/postRatingProxy",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            document.getElementById("testAjax").innerHTML = msg.d;
        }
    });
}

我的页面方法看起来像:

[WebMethod]
public static string postRatingProxy()
{
    return .......postRating();
}

然后用户控制方法看起来像:

public static string postRating()
{
    return "git er done";
}

我在某处看到有人建议这种方法。虽然我非常迷茫,当它是静态的时如何从 Page 方法中检索我的 UserControl 方法。是否可以从静态方法中检索 UserControl 还是我只是陷入了死胡同?

【问题讨论】:

    标签: c# asp.net ajax webmethod


    【解决方案1】:

    是否可以从静态方法中检索 UserControl 或 我是不是走入了死胡同?

    不,这是不可能的。 ASP.NET PageMethod 是静态的,不会让您访问任何用户控件。这样做的原因是简单的。当您使用 jQuery 执行 AJAX 请求时,没有 ViewState 被发送到服务器,因此用户控制的概念几乎没有意义。如果您需要访问页面方法中的某些值,请将此值作为 AJAX 请求中的参数发送:

    data: JSON.stringify({ someParameter: 'some value you could take from wherevr you want' }),
    

    【讨论】:

    • 如果你是对的,那么其他人在骗我。手指指向 -> stackoverflow.com/questions/3392345/…
    • 感觉很愚蠢,但我想通了。一旦我花了一些时间从这个问题中冷静下来,我就回来并立即解决了这个问题。基本上我所要做的就是:调用 return USERCONTROLNAME.postRating();由于它是静态的,因此您可以直接从类中访问它。失败我很抱歉打扰。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2011-03-16
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多