C# 如何在标记中“绑定”标签的文本属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/73484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to 'bind' Text property of a label in markup
提问by Adam Vigh
Basically I would like to find a way to ddo something like:
基本上我想找到一种方法来做类似的事情:
<asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label>
I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution. (MyProperty is a string property) cheers
我知道我可以从后面的代码中设置它(编写 lId.Text = MyProperty),但我更喜欢在标记中进行设置,但我似乎无法找到解决方案。(MyProperty 是一个字符串属性)欢呼
采纳答案by mrflippy
Code expressions are an option as well. These can be used inside of quotes in ASP tags, unlike standard <%= %> tags.
代码表达式也是一种选择。与标准的 <%= %> 标签不同,这些可以在 ASP 标签的引号内使用。
The general syntax is:
一般语法是:
<%$ resources: ResourceKey %>
There is a built-in expression for appSettings:
appSettings 有一个内置表达式:
<%$ appSettings: AppSettingsKey %>
More info on this here: http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
更多信息在这里:http: //weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
回答by Akselsson
Call lID.Databind() from code-behind
从代码隐藏调用 lID.Databind()
回答by John Sheehan
Leave the markup as is and make a call to Page.DataBind(); in your code behind.
保持标记不变并调用 Page.DataBind(); 在你后面的代码中。
回答by Serhat Ozgel
<asp:Label id="lID" runat="server"><%= MyProperty %></asp:Label>
since asp.net tags do not allow <% %> constructs, you cannot use Text="<%= MyProperty %>".
由于asp.net 标记不允许<% %> 构造,因此不能使用Text="<%= MyProperty %>"。
回答by DevelopingChris
<div> <%=MyProperty"%></div>
回答by Mark S. Rasmussen
You can do
你可以做
<asp:Label runat="server" Text='<%# MyProperty %>' />
And then a Page.DataBind() in the codebehind.
然后是代码隐藏中的 Page.DataBind()。
回答by Frederik Vig
When you use <%# MyProperty %> declaration you need to databind it, but when using <%= MyProperty %> you don't (which is similar to just writing Response.Write(MyProperty).
当您使用 <%# MyProperty %> 声明时,您需要对其进行数据绑定,但是在使用 <%= MyProperty %> 时您不需要(这类似于仅编写 Response.Write(MyProperty))。
回答by Brian
You can do this:
你可以这样做:
<asp:Label ID="lblCurrentTime" runat="server">
Last update: <%=DateTime.Now.ToString()%>
</asp:Label>