一. <%%>
之间可以写服务器代码(这里是C#代码)。
变量在C#中需要被声明为public或protected。
<%for (int i = 1; i <= p; i++)
{
Response.Write("--" + i);
} %>--
+aspx.cs如下:
protected int p = 10;
特别注意:服务器控件中<%%>语法无效。
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
二. <%#%>
数据绑定,这种格式是asp.net下特有的,必须要调用DataBind()方法才会执行。
并且实现前台使用C#中的变量,变量在C#中需要被声明为public或protected。
(调用整个页面Page.DataBind(),在这种情况下不管是服务器控件还是客户端控件都会被绑定。)
Server Control:<asp:Button ID="Button1" runat="server" Text="<%#zz%>" />
Client Control:<input type="button" value="<%#zz%>" />
+aspx.cs代码如下:
protected string zz = "111";
protected void Page_Load(object sender, EventArgs e)
{
Page.DataBind();//整个页面都绑定数据
//this.DataBind();//等效与上一行
//btn.DataBind();//只绑定某个控件
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
三. <%=%>
这个常用于前台调用C#中的方法,方法必须有返回值,且需要被声明为public或protected。
也可以调用C#中的变量,变量在C#中需要被声明为public或protected。
服务器控件和客户端控件中都可以使用。
<asp:Label ID="label" runat="server"><%=fun()%></asp:Label>
<label><%=fun()%></label>
<%=zz%>
<%:zz%><%--等价于上一句--%>
+aspx.cs代码如下:
protected string zz = "111";
protected string fun()
{
return "C#中的方法";
}
特别注意:函数名后面有括号但是没有分号!
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
四. <%$%>
这种形式主要用于对web.config文件的键值对进行绑定,通常用于连接数据库的字符串。
特别注意:1.绑定的只能是服务器控件
2.只能绑定到服务器控件的某个属性上。
(暂时还没有用过,先把别人的经验capy过来~)
<asp:TextBox runat="server" ID="cc" Text="<%$ConnectionStrings:pubs%>"></asp:TextBox>
web.config文件如下:
<connectionStrings>
<add name="pubs" connectionString="Server=.;database=pubs;uid=sa;pwd=" providerName="System.Data.SqlClient"/>
</connectionStrings>
如果使用客户端的控件
<input type="text" value="<%$ConnectionStrings:pubs%>"/><%--错误--%>
或者不绑定到服务器控件的某个属性上
<asp:TextBox runat="server" ID="TextBox1"><%$ConnectionStrings:pubs%></asp:TextBox><%--错误--%>
运行都会出现相同的错误。
补充:
1. 上面一、二、三形式也可以写在js脚本中,不会报错。
2. 如果为服务器控件绑定了数据源,前台的写法通常是:
<%# Eval("查询出的字段")%>
+aspx.cs代码如下:
DataSet ds;
DataList.DataSource = ds;
DataList.DataBind();