how to call a variable in code behind to aspx page

后端 未结 9 1863
暗喜
暗喜 2020-11-27 07:06

i know i have seen this but cant recall the correct way of doing it... basically i have a string variable called \"string clients\" in my .cs file.. but i wasn\'t to be able

相关标签:
9条回答
  • 2020-11-27 07:31

    The field must be declared public for proper visibility from the ASPX markup. In any case, you could declare a property:

    
    private string clients;
    public string Clients { get { return clients; } }
    
    

    UPDATE: It can also be declared as protected, as stated in the comments below.

    Then, to call it on the ASPX side:

    <%=Clients%>

    Note that this won't work if you place it on a server tag attribute. For example:

    <asp:Label runat="server" Text="<%=Clients%>" />

    This isn't valid. This is:

    <div><%=Clients%></div>

    0 讨论(0)
  • 2020-11-27 07:35

    The HelloFromCsharp.aspx look like this

     <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <p>
           <%= clients%>
        </p>
        </form>
    </body>
    </html>
    

    And the HelloFromCsharp.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace Test
    {
        public partial class HelloFromCsharp : System.Web.UI.Page
        {
            public string clients;
            protected void Page_Load(object sender, EventArgs e)
            {
                clients = "Hello From C#";
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 07:37

    You need to declare your clients variable as public, e.g.

    public string clients;
    

    but you should probably do it as a Property, e.g.

    private string clients;
    public string Clients{ get{ return clients; } set {clients = value;} }
    

    And then you can call it in your .aspx page like this:

    <%=Clients%>
    

    Variables in C# are private by default. Read more on access modifiers in C# on MSDN and properties in C# on MSDN

    0 讨论(0)
提交回复
热议问题