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

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

问题描述

我试图连接属性中的一个字符串。我收到一个错误。我认为它与我的 Eval 有关。有没有适当的方法来连接字符串,或者这是不可能的。我相信这个问题是我设置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控件属性使用数据绑定表达式。您需要将数据绑定表达式中的所有内容都移动到数据绑定表达式中。

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

 <%#EXPRESSION%> 

基本上,对于Web控件属性使用数据绑定表达式的规则是表达式必须是

 < asp:HyperLink ID =lbrunat =server
Text ='<%#EXPRESSION%>'
NavigateUrl ='<%#EXPRESSION%>'/>

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



以下是正确的语法:

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

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

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


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") %>'/>

解决方案

Short answer: NavigateUrl='<%# Eval("Key.Id", "ViewItem.aspx?id={0}") %>'

Longer explanation:

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 %>

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 %>' />

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.

Here is the correct syntax:

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

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天全站免登陆