3

我有Default.aspx一个单独的代码文件:

public partial class _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       public string hello = "hello world"
   }
}

我想在我尝试使用 <%=hello%> 但不起作用的默认页面中显示此内容。我究竟做错了什么?

4

6 回答 6

4
 protected void Page_Load(object sender, EventArgs e)
 {
   string hello = "i need more practice";
   Response.Write(hello);
 }
于 2012-06-06T17:58:05.923 回答
4

试试这个:

public partial class _Default : System.Web.UI.Page
{
    public string hello = "hello world";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}
于 2012-06-06T17:58:08.707 回答
3

也试试

页面

<%= this.hello%>

.cs 代码隐藏文件

public partial class _Default : System.Web.UI.Page
{
    public string hello = "hello world";
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

只要写这个就可以完成任务

Response.Write("Hello World");
于 2012-06-06T17:58:04.240 回答
3

您的代码不会按原样编译。试试这个:

public partial class _Default : System.Web.UI.Page
{
    public string Hello { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        Hello = "hello world";
    }
}
于 2012-06-06T17:59:02.570 回答
2

请改用标签。您将能够轻松地格式化输出

 in your .aspx
 <body>
   <asp:Label runat="server" ID="HelloLabel"></asp:Label>
 </body>

//code behind
protected void Page_Load(object sender, EventArgs e)
{
  string hello = "i need more practice";
  HelloLabel.Text = "hello";
}
于 2012-06-06T18:01:00.817 回答
2

您需要将其实际写入标记。您可以通过创建标签(或文字)来做到这一点: <asp:Label ID="helloLabel" runat="server" Text = "<%#HelloWorld()%> ></asp:Label> 然后您将需要一个名为 HelloWorld 的函数,它返回一个字符串

private string HelloWorld()
{
    string hello = "Hello World";
    return hello;
}

或者您可以直接从函数中设置标签文本。

helloLabel.Text = "Hello World";

于 2012-06-06T18:02:19.620 回答