如何从 WebMethod 访问全局变量?
我有以下全局变量:
private ArrayList listSelectedUnavailables
{
get
{
return (ArrayList)ViewState["listSelectedUnavailables"];
}
set
{
ViewState["listSelectedUnavailables"] = value;
}
}
我可以在网络表单的每个过程中使用它。
但是,我需要在同一个 WebForm 中的 WebMethod 中使用它,但它似乎无法识别任何全局变量。那么:
如何从 WebMethod 访问全局变量?
I have the following global variable:
private ArrayList listSelectedUnavailables
{
get
{
return (ArrayList)ViewState["listSelectedUnavailables"];
}
set
{
ViewState["listSelectedUnavailables"] = value;
}
}
I can work with it in every single procedure of the webform.
However, I need to use it in a WebMethod that I have in the same WebForm, but it seems not to identify any of the global variables. So:
How can I access a global variable from a WebMethod?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将该值存储在 Viewstate 中,该值对 WebMethod 不可用,请尝试使用“Session”变量。
You are storing the value in the Viewstate, which will not be available to the WebMethod, try using a 'Session' variable instead.
ViewState
属性取决于页面 (.aspx) 回发视图状态,这就是存储“变量”的位置。WebMethod
不包括整个页面回发(如果有回发的话),因此没有可供读取的视图状态。相反,您可能想要使用会话变量,例如:会话将变量存储在 Web 服务器的内存中(但与特定的浏览器会话相关)。这有其自身的缺点,例如对工作进程重置、负载平衡考虑等不稳定。
A
ViewState
property depends on having a page (.aspx) post back a view state, that's where your "variable" is stored. AWebMethod
does not include the full page postback (if any post back at all) and so there is no view state for it to read from. Instead you may want to use a session variable like:The session stores the variable in the web server's memory (but related to a specific browser session). This has it's own draw-backs, such as being volatile to a worker process reset, load balancing cosiderations, etc.
您无法在 Web 方法中访问非静态属性。如果您的业务规则允许您应该使用静态属性
you cannot access a non static property within a web method. if your business rule allows that you should use a static property
是的,你可以。
' VB .net 示例
_
Public Shared Function LoadController(ByVal serial As String) As String
// C# 示例:
[WebMethod(描述 = "Proiecto", CacheDuration = 0)]
公共静态字符串LoadController(字符串序列)
{
}
Yes you can.
' VB .net sample
_
Public Shared Function LoadController(ByVal serial As String) As String
// C# sample:
[WebMethod(Description = "Proiecto", CacheDuration = 0)]
public static string LoadController(string serial)
{
}