ASP.NET TextBox-是否可以使用行代码& lt;%%& gt;初始化文本属性 [英] ASP.NET TextBox - is it possible to initialize text attribute with in line code <% %>

查看:72
本文介绍了ASP.NET TextBox-是否可以使用行代码& lt;%%& gt;初始化文本属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我需要使用其他地方的属性来初始化文本框元素的text属性,而实际上我可以仅通过代码来完成此操作,但是如果可以这样做,将会更加方便:


I need to initialize the text attribute of the text box element with a property from some where else when actually I can simply do this from code but it will be much more convenient if it possible to do it like this:

<asp:TextBox runat="server" Text="<%= new ContextItem("title").Value %>" />

很遗憾,以上操作无法完成..
问题是此文本框元素会在页面中多次自我重复,而我的问题是:

Unfortunately the above can't be done..
The issue is that this text box element repeats it self several times in the page and my question is:

是否有任何建议使它更整洁,然后在后面的代码中一次又一次地编写它?
感谢,阿德勒

Are there any suggestions how to make it cleaner then to write it again and again in the code behind?
Thank, Adler

推荐答案

好,所以这里的基本问题是,如果您使用内联表达式,则不能在绑定之外使用它来设置服务器端控件的属性上下文(使用绑定表达式).我推断这可能是由于评估这些内联表达式的时机所致.但是,您可以通过这种方式呈现客户端标记.如果您只想将功能保留在aspx文件中,则可以使用此方法.

OK so the basic problem here is that if you use an inline expression you can NOT use it to set a property of a server-side control outside of a binding context (using a binding expression). I have inferred that this is probably because of the timing of the evaluation of these inline expressions. You can, however, render client-side markup in this way. If you want to keep the functionality purely in your aspx file, this is the way to do it.

根据贾斯汀·凯斯(Justin Keyes)的输入,似乎可以使用绑定表达式来设置属性.您需要手动调用 Page.DataBind()来触发文本框来评估表达式(请参见下面的答案).

Based on input from Justin Keyes, it appears it IS possible to use a binding expression to set the property. You need to manually invoke Page.DataBind() to trigger the textbox to evaluate the expression (see answer below).

例如:

<asp:Label ID="lbl" runat="server" Text="<%= Now.ToShortDateString() %>"  />

将产生以下输出:

<%= Now.ToShortDateString()%>

<%= Now.ToShortDateString() %>

另一方面:

<%=< span>"&Now.ToShortDateString()&</span>"%>

将产生以下输出:

2011/7/27

7/27/2011

解决此问题的正常"方法只是在 Page.Load 事件处理程序或其他适当的事件处理程序中设置 Label.Text 属性,具体取决于您的需求如下.我认为这是大多数人更喜欢这样做的方式,并且我认为这是最容易理解的.

The "normal" way to solve this problem is just to set the Label.Text properties in a Page.Load event handler or another appropriate event handler depending on your needs, as below. This is the way I believe most people would prefer to do it, and is most easily understandable in my opinion.

标记:

<asp:Label ID="lbl" runat="server" />

代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    lbl.Text = Now.ToShortDateString()
End Sub

这篇关于ASP.NET TextBox-是否可以使用行代码&amp; lt;%%&amp; gt;初始化文本属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆