【发布时间】: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 调用该方法............需要帮助。
【问题讨论】:
-
您无法从 Web 方法访问控件。 stackoverflow.com/questions/2133194/… 只有在页面的生命周期中,才会实例化
Page(及其所有控件)的实例。