how to call a variable in code behind to aspx page

后端 未结 9 1862
暗喜
暗喜 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:20

    Make sure that you have compiled your *.cs file before browsing the ASPX page.

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

    I would create a property to access the variable, like this:

    protected string Test
    {
        get; set;
    }
    

    And in your markup:

    <%= this.Test %>
    
    0 讨论(0)
  • 2020-11-27 07:22

    In your code behind file, have a public variable

    public partial class _Default : System.Web.UI.Page
    {
        public string clients;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            // your code that at one points sets the variable
            this.clients = "abc";
        }
    }
    

    now in your design code, just assign that to something, like:

    <div>
        <p><%= clients %></p>
    </div>
    

    or even a javascript variable

    <script type="text/javascript">
    
        var clients = '<%= clients %>';
    
    </script>
    
    0 讨论(0)
  • 2020-11-27 07:23

    First you have to make sure the access level of the variable is protected or public. If the variable or property is private the page won't have access to it.

    Code Behind

    protected String Clients { get; set; }
    

    Aspx

    <span><%=Clients %> </span>
    
    0 讨论(0)
  • 2020-11-27 07:25

    For

    <%=clients%>
    

    to work you need to have a public or protected variable clients in the code-behind.

    Here is an article that explains it: http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

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

    You can access a public/protected property using the data binding expression <%# myproperty %> as given below:

        <asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label>
    

    you should call DataBind method, otherwise it can't be evaluated.

        public partial class WebForm1 : System.Web.UI.Page
        {
         public string CodeBehindVarPublic { get; set; }
          protected void Page_Load(object sender, EventArgs e)
            {
              CodeBehindVarPublic ="xyz";
           //you should call the next line  in case of using <%#CodeBehindVarPublic %>
    
              DataBind();
            }
    

    }

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