【问题标题】:issue regarding access page control from static method asp.net 4.0关于从静态方法 asp.net 4.0 访问页面控制的问题
【发布时间】:2012-06-06 12:35:06
【问题描述】:

我通过 jquery 调用我的服务器端方法,并尝试从该方法访问文本框数据。这是我的示例代码

    [WebMethod]
    public static PayPalCart CreatePayPalFields()
    {
        Page CurPage = HttpContext.Current.Handler as Page;
        string tt = ((TextBox)CurPage.FindControl("txtBillAddress1")).Text; 
    }

我从静态方法访问控件时遇到错误,错误消息是对象引用未设置为对象的实例。然后我搜索谷歌以找到更好的解决方案然后我得到了一个扩展方法,它将遍历控件集合并在找到时返回控件。代码是这样的

public static T BetterFindControl<T>(this Control root, string id) where T : Control
{
    if (root != null)
    {
        if (root.ID == id) return root as T;

        var foundControl = (T)root.FindControl(id);
        if (foundControl != null) return foundControl;

        foreach (Control childControl in root.Controls)
        {
            foundControl = (T)BetterFindControl<T>(childControl, id);
            if (foundControl != null) return foundControl as T;

        }
    }

    return null;
}

我也从静态方法中使用上述例程,例如

    [WebMethod]
    public static PayPalCart CreatePayPalFields()
    {
        Page CurPage = HttpContext.Current.Handler as Page;
        string sData = CurPage.BetterFindControl<TextBox>("txtDeliveryFName").Text; 
    }

但仍然没有运气....从静态方法访问控件时仍然遇到相同的错误,并发现 CurPage 没有控件。请建议我该怎么做。告诉我从静态方法访问控制的出路,因为方法必须是静态的原因我通过 jquery 调用该方法............需要帮助。

【问题讨论】:

标签: jquery asp.net


【解决方案1】:

您无法通过此 ajax 调用访问该页面,原因很简单,因为发生此调用时该页面不存在于任何地方。

您可以做的是通过ajax调用发送您喜欢检查的参数,并使用javascript获取它们并发送它们。

多说几句关于 call 的作用。

string sData = CurPage.BetterFindControl<TextBox>("txtDeliveryFName").Text;

这是对 .Form 发布数据的最终调用,以读取由 id 为 txtDeliveryFName 的控件发送的内容。在您的 ajax 调用中,没有发布整个页面,另一方面,您可以控制哪些数据将通过 javascript 发布到 webmethod。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    相关资源
    最近更新 更多