asp.net中的<% %>用法

1、<% %>

服务器控件中不能有<%%>语法

<%
        int a = 2;
        int b = 3;
        int c = a + b;
        Response.Write(c);
 %>

2、<%#%>

asp.net下特有的,它是控件数据绑定的语法,且必须要调用该控件的DataBind()方法才执行

<div>
Server Control:<asp:TextBox ID="TextBox1" runat="server" Text="<%#text%>"></asp:TextBox><br /><!--Server Control-->
Client Control:<input type="text" id="textbox2" value="<%#text%>" /><!--Client Control-->
 </div>
 protected string text;//注意这里必须申明为public或protected,否则aspx页面(子类)无法访问
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.text = "aaaaaaaaaaaaa";
                this.TextBox1.DataBind();//或this.DataBind();              
            }
        }

3、<%= %>(同<%: %>)

public string  DisplayStr()//注意这里必须要有返回值,否则将会发生运行时错误
        {
            return "bbbb";
        }
 <label id="label1"><%=DisplayStr()%></label><br />
  <label id="label2" runat="server"><%=DisplayStr()%></label>

或者

<input type="text" id="a"  value=<%=DisplayStr()%> />
          <input id="Text1" type="text"  runat="server" value=<%=DisplayStr()%> />

4、<%$ %> 

这种形式主要用于对web.config文件的键值对进行绑定:通常用于连接数据库的字符串

<asp:TextBox runat="server" ID="cc" Text="<%$ConnectionStrings:pubs%>"></asp:TextBox>
<connectionStrings>
    <add name="pubs" connectionString="Server=.;database=pubs;uid=sa;pwd=" providerName="System.Data.SqlClient"/>
  </connectionStrings>
原文地址:https://www.cnblogs.com/danznb/p/3508137.html