简体   繁体   中英

How do I access a C# string on my aspx page?

I have declared a String on code-behind like so:

String myString = "Hi SO!";

How do I then print this on my aspx page?

<%= myString %> doesn't appear to be working.

CS0103: The name 'myString' does not exist in the current context

This may depend on where you have declared your string.

Make sure you are not declaring your string inside a method, the string should be a global variable inside the class

Also ensure the string is protected or public

确保您的字符串是受保护的公共的,以便后代类可以看到它。

The access modifier needs to be at least protected .

protected String myString = "Hi SO!";

The reason behind is that each .aspx page inherits from the code-behind class.

The easiest way I've found to do this is create the string in my code behind page, then add a label on the aspx page. On the code behind page, you will need to write some code like this:

string myString = "some value";
label1.Text = myString;

Make sure this is in the Page_Load event in the code behind page, depending on what you are trying to do. In my case I wanted the string to be called at runtime when the page loads up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM