关于从静态方法asp.net 4.0访问页面控制的问题
我通过jquery调用我的服务器端方法,并且从该方法我试图访问文本框数据。 这是我的示例代码
[WebMethod] public static PayPalCart CreatePayPalFields() { Page CurPage = HttpContext.Current.Handler as Page; string tt = ((TextBox)CurPage.FindControl("txtBillAddress1")).Text; }
我从静态方法访问控件时收到错误,错误消息是未将对象引用设置为对象的实例 。 然后我搜索谷歌找出更好的解决方案然后我有一个扩展方法,将循环通过控件收集和返回控制,如果找到。 代码就像
public static T BetterFindControl(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(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("txtDeliveryFName").Text; }
但仍然没有运气….从静态方法访问控件仍然得到相同的错误,发现CurPage没有控制权。 请建议我该怎么办。 告诉我一个从静态方法访问控制的方法,因为方法必须是静态的,因为我通过jquery调用该方法………需要帮助。
您无法通过此ajax调用访问该页面,这很简单,因为在此调用发生时,该页面不存在。
你可以做的是通过ajax调用发送你想要检查的参数,并使用javascript来获取它们并发送它们。
更多关于什么叫做的话。
string sData = CurPage.BetterFindControl("txtDeliveryFName").Text;
这是对.Form post数据的最后调用,用于读取id为txtDeliveryFName的控件发送的内容。 在你的ajax调用中没有整页的post,另一方面你控制通过javascript将什么数据发布到webmethod。