关于<%= str%>和<%# str %>两种方式的应用实例

来源:互联网 发布:java布局思想 编辑:程序博客网 时间:2024/06/06 02:56
两种绑定方式上,他们的约束基本相同,都要求与属性匹配,出现在他们可以出现的位置。后者的使用位置更广泛,尤其是支持服务器端控件和绑定数据集合。后台代码方面,后者需要调用DataBind才能完成绑定,前者则没有这方面要求。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %><!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>    <script type="text/javascript">        function fun() {            //////前台位置1,JavaScript代码中             var str = "<%= DateTime.Now %>";                                                      var str2 = "<%# DateTime.Now %>";   //只有Page.DataBind();才能生效                     alert("=绑定:" + str + "   #绑定:" + str2);        }    </script></head><body onload="fun()">    <form id="form1" runat="server">    <div>       <%--前台位置2,服务器端控件属性或HTML标签属性 --%>        <input type="text" value="<%= GetVariableStr %>" />             <input type="text" value="<%# GetVariableStr %>" />        <br />         <%--Label1属于嵌套类控件,Label1确实显示了正确的结果,TextBox属于非嵌套类控件,TextBox如果用这种方式,将会产生编译错误--%>        <asp:Label ID="Label1" runat="server"><%= GetVariableStr %></asp:Label>               <asp:Label ID="Label2" runat="server" Text="<%# GetVariableStr %>"></asp:Label>        <br />        <%--前台位置3,Html显示内容的位置>--%>        <%= GetVariableStr %><%= GetFunctionStr() %>        <%# GetVariableStr %><%# GetFunctionStr() %>    </div>    </form></body></html>

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class test : System.Web.UI.Page{    public string GetVariableStr;//注意变量的修饰符    protected void Page_Load(object sender, EventArgs e)    {        GetVariableStr = "hello world from variable";        Page.DataBind();    }    protected string GetFunctionStr()//注意返回值的修饰符    {        return "hello world from Function";    }}

0 0
原创粉丝点击