引用 .aspx 页面上的代码隐藏属性?
在 .aspx 页面上,将服务器控件的属性链接到页面类(其代码隐藏)的属性的最佳方法是什么?我读到的唯一方法是使用数据绑定:
<asp:TextBox ID="txt" runat="server" Text='<%# Me.SomePropOfMine %>' />
然后从代码隐藏中调用 Me.txt.DataBind()
或 Me.Databind()
。有没有什么方法可以单独在 .aspx 页面上建立这种关系,或者如果您有许多控件要绑定(而不绑定整个页面),则可以简化过程?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以
Databind()
整个Me
或容器控件(您也可以在所需控件周围添加PlaceHolder
控件)。因为DataBind()
在子控件上递归进行。如果您不需要 DataBinding,除此之外,更好的方法是使用代码表达式绑定器
http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
这允许您可以使用
<%$ Code: Me.Property %>
而不是<%# Me.Property %>
。如果您根本不了解表达式构建器,请查看此介绍文章,了解有关它们的更多信息:
https://web.archive.org/web/20210304125044/https://www.4guysfromrolla.com/articles/022509-1.aspx
请注意 等 Web 控件...
<%= Me.Property %>
不适用于PS
Code
表达式生成器的唯一缺点是您无法获得智能感知。我通常通过在标记内写入<%= Me.TestSomething %>
来解决此问题以获得智能感知,然后将<%=
替换为<%$ 代码:
完成后。烦人,但如果您不想走 DataBind() 路线(并且您不应该导致它可能与您想要执行的现有实际数据绑定冲突。相信我,尝试使这些工作是地狱),那么这是要走的路。You can
Databind()
entireMe
or a container control (you can add aPlaceHolder
control around your desired controls also). becauseDataBind()
goes recursively on Child controls.A better approach if you don't need DataBinding except for this is to use Code Expression Binder
http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
This allows you to use
<%$ Code: Me.Property %>
instead of<%# Me.Property %>
.For more about expression builders in general if you don't know them at all check this intro post:
https://web.archive.org/web/20210304125044/https://www.4guysfromrolla.com/articles/022509-1.aspx
Note that
<%= Me.Property %>
will NOT work on web controls like<asp:TextBox ...
and such...P.S.
The only drawback with
Code
expression builder is that you get no intellisense. I usually work around this by writing<%= Me.TestSomething %>
inside the markup to get my intellisense, and then replace<%=
with<%$ Code:
when done. Annoying, but if you don't want to go the DataBind() route (and you shouldn't cause it may conflict with existing real data binding you want to do. Trust me, trying to make those work is hell), then this is the way to go.有两件事:
There are two things:
如果我确实需要这样做,我会使用 代码表达式生成器。
但问题是 - 为什么要在标记中而不是在代码隐藏中设置属性?如果它们是动态的并且与逻辑相关(很可能是),那么您应该将它们设置在代码后面,即使这看起来不方便 - 这会将逻辑保留在一个地方,而将标记保留在另一处。
If I would ever actually need to do this, I would use CodeExpressionBuilder.
But question is - why do you want to set properties in markup and not in code behind? If they are dynamic and related to logic (and probably they are), then you should set them in code behind even if that looks unconvenient - that would keep logic in one place and markup in other.