Accessing control attributes from static function
Here's what I've got:
<textarea id="TextArea1" rows="6" cols="20" runat="server"></textarea>
and in the code-behind:
partial class _Default : System.Web.UI.Page
{
[Webmethod()]
public static void Data(int TestNum)
{
if (TestNum > 0) TextArea1.InnerText = "hello world";
}
}
And I'm getting the follo开发者_JAVA技巧wing error:
Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
As I understand it, I need to declare an instance of the class within my shared function like so:
_Default NewInstance = New _Default();
NewInstance.TextArea1.InnerText = "hello world";
My question then is, is there any way I can avoid doing this? Is this bad practice and what kind of memory or performance penalty will I incur for doing this?
Thank you.
Edit: I should mention that the Static declaration is necessary for WebMethods
If the intent is to change the textarea on the page via an asynchronous callback, your best bet is to wrap it in an UpdatePanel or use something like JQuery to do the ajax call by hand. In the latter case you would only reference the textarea from the javascript and fetch the content asynchronously.
You need to remove the static
modifier from your Data
method.
Don't make it static...
[Webmethod()]
public string Data(int TestNum)
{
TextArea1.InnerText = "hello world";
}
Let's call these things what they are. They are Page Methods and they do need to be declared static(C#)/Shared(VB).
The reason these page methods are not able to access the page variables is: you have to think about it as client and server. Server gets a request from client. Server serves up page to client, doing any "Polishing" on the server. Once the server sends the data to the client, the server forgets the "Polished" content even exists. Your client side page is now an orphan. The server is too busy spewing out more orphans all the time. Your server is such a whore. It has no time to keep up with each instance of a page it gives birth too, especially if you have millions of people accessing your server each day/hour. The way the client refreshes the servers memory in .Net is usually through mechanisms like postbacks, viewstate, etc. Otherwise, the server say, nope, you ain't my child.
In comes ajax, and Page Methods. Ajax gathers the key information that the server needs to do the base processing required by the application and sends back information. The communication medium for this is usually JSON for Page methods. So now the server becomes just a calculator or storage for information, but the client still needs know what information to send, how to send it in order for the server to do anything for you. That's the layman's explanation for things.
精彩评论