使用c#表达式定义服务器标签属性值

发布于 2024-09-12 14:32:18 字数 194 浏览 5 评论 0 原文

是否可以从 ac# 表达式设置服务器标记的属性,即类似的内容

<asp:TextBox Width='<%= [some c# expression] %>'/> 

我虽然这非常简单,但我无法运行这样的表达式。

感谢您的帮助

瑞安

Is it possible to set the property of a server tag from a c# expression, i.e. something like

<asp:TextBox Width='<%= [some c# expression] %>'/> 

?

I though this would be pretty straightforward, but I can't get such an expression to run.

Thanks for any help

Ryan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

漫雪独思 2024-09-19 14:32:18

是的,这是可能的。您需要确保控件运行服务器端 (runat="server"),但具体取决于您尝试在表达式中计算的内容。

只要表达式返回一个字符串,就应该没问题。

<asp:TextBox id="txt" runat="server" Width='<%= (10 * 10).ToString() %>px'/> 

这将导致浏览器中出现 width='100'

更新:

以上是完全错误的。您不能以这种方式将服务器端代码呈现块(<%%><%=%>)放入服务器端控件标记中(因为它已经是运行服务器端)。

为了动态控制该值,这需要在代码隐藏中或在单独的渲染块中完成:

<%
  txt.Width = (10 * 10).ToString() + "px";
%>
<asp:TextBox id="txt" runat="server" /> 

请参阅供参考。

Yes, this is possible. You need to make sure the control runs server side (runat="server"), but depends on exactly what you are trying to evaluate in the expression.

So long as the expression returns a string, it should be fine.

<asp:TextBox id="txt" runat="server" Width='<%= (10 * 10).ToString() %>px'/> 

This will result in a width='100' in the browser.

Update:

The above is completely wrong. You cannot put server side code render blocks (<%%> and <%=%>) in a server side control markup in this manner (since it already is a run server side).

In order to dynamically control the value, this needs to be done either in codebehind or within separate render blocks:

<%
  txt.Width = (10 * 10).ToString() + "px";
%>
<asp:TextBox id="txt" runat="server" /> 

See this and this for reference.

君勿笑 2024-09-19 14:32:18

请注意您绑定的类型。

例如,

<asp:TextBox runat=server ID=C_TB_MyTB 
        Text=<%# MyText %> 
        Width=<%# MyWidth %>
    ></asp:TextBox>

用 绑定这个文本框是

protected string MyWidth="300";
protected string MyText = "Bla bla bla...";

行不通的,而 :

protected int MyWidth=300;
protected string MyText = "Bla bla bla...";

可以...

对你来说是好的代码,

Beware of the type you bind to .

for instance

<asp:TextBox runat=server ID=C_TB_MyTB 
        Text=<%# MyText %> 
        Width=<%# MyWidth %>
    ></asp:TextBox>

Binding this textbox with

protected string MyWidth="300";
protected string MyText = "Bla bla bla...";

won't work , whereas :

protected int MyWidth=300;
protected string MyText = "Bla bla bla...";

will do...

good code to you,

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文