String concatenation in ASP.NET attributes

I am trying to execute a string inside an attribute. I get an error message. I think this is due to my Eval . Is there a suitable way to concat strings, or is it just not possible. I believe the problem is where I install NavigateUrl.

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

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

More detailed explanation:

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

First of all, this is a data binding expression:

 <%# EXPRESSION %> 

In principle, the rule of using a data binding expression for a web control attribute is that the expression should be the only one in the attribute:

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

So your first Text attribute is correct. But your second NavigateUrl attribute is incorrect. Since 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}") %>'/> 

Note that we use the 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")) %>'/> 
+3
source

Here is what I do when I have something in gridview like this:

 <img src='<%# GetDisImageLink(Eval("Disabilities").ToString()) %>' alt="Disabilities" /> 

[CS code code]

 public string GetDisImageLink(string dis) { return "../../Content/Images/CardContactInfo/" + (dis.Trim() == "Y" ? "DIS.png" : "Blank.png"); } 
+1
source

Try this instead:

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

You do not need to concatenate

-2
source

Source: https://habr.com/ru/post/1393259/


All Articles