在 ASP.NET 属性中组合字符串 [英] Combining Strings in ASP.NET Attributes

查看:15
本文介绍了在 ASP.NET 属性中组合字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在属性中连接一个字符串.我收到一个错误.我认为这与我的Eval有关.是否有正确的方法来连接字符串,或者这是不可能的.我认为问题在于我设置 NavigateUrl 的位置.

I am trying to concat a string inside the attribute. I get an error. I think that it is related to my Eval. Is there a proper way to concat strings, or is this just not possible. The problem I believe is where I set the NavigateUrl.

<asp:HyperLink ID="lb" 
               runat="server" 
               Text='<%#Eval("Key.Id") %>' 
               NavigateUrl='ViewItem.aspx?id=' + '<%# Eval("Key.Id") %>'/>

推荐答案

简短回答:NavigateUrl='<%# Eval("Key.Id", "ViewItem.aspx?id={0}")%>'

更长的解释:

您代码中的问题是您仅对部分 Web 控件属性使用数据绑定表达式.您需要移动数据绑定表达式中的所有内容.

The problem in your code is that you are use data binding expression only for part of your web control attribute. You need to move everything inside the data binding expression.

首先,一个数据绑定表达式是这样的:

First of all, a data binding expression is this:

<%# EXPRESSION %>

基本上,为 Web 控件属性使用数据绑定表达式的规则是该表达式必须是属性中唯一的内容:

Basically the rule for using a data binding expression for a web control attribute is that the expression must be the only thing in the attribute:

<asp:HyperLink ID="lb" runat="server" 
  Text='<%# EXPRESSION %>'
  NavigateUrl='<%# EXPRESSION %>' />

所以您的第一个属性 Text 是正确的.但是您的第二个属性 NavigateUrl 不正确.因为你把 ViewItem.aspx?id= 作为属性的值,把 + '<%# Eval("Key.Id") %>' 留在外面任何属性,但在控制标签内.

So your first attribute, Text, is correct. But your second attribute, NavigateUrl is not correct. Because you put ViewItem.aspx?id= as the value for the attribute, leaving + '<%# Eval("Key.Id") %>' outside any attribute but inside the control tag.

正确的语法如下:

<asp:HyperLink ID="lb" runat="server" 
  Text='<%# Eval("Key.Id") %>' 
  NavigateUrl='<%# Eval("Key.Id", "ViewItem.aspx?id={0}") %>'/>

请注意,我们使用格式字符串作为 Eval() 的第二个参数.这等效于以下更明确的语法:

Notice that we are using a format string as the second parameter for Eval(). This is equivalent to the following, more explicit, syntax:

<asp:HyperLink ID="lb" runat="server" 
  Text='<%# Eval("Key.Id") %>' 
  NavigateUrl='<%# String.Format("ViewItem.aspx?id={0}", Eval("Key.Id")) %>'/>

这篇关于在 ASP.NET 属性中组合字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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