Concatenate two or more strings in inline code ASP.NET

為{幸葍}努か 提交于 2019-12-07 02:09:23

问题


I am trying to place a * next to the name based on a condition.

My code :

 <asp:Label ID="lblOne" runat="server"   Text= '<%# Eval("name") + ((Eval("StatusId").Equals(0) && Eval("assignfilename") == null) ? " *" : "") %>' > </asp:Label>

Thanks

BB


回答1:


If you're pushing the limits of what you can easily handle with inline code, you could always write a function instead. Then you can do something like:

 <asp:Label ID="lblOne" runat="server"   Text= '<%# EmitSomeText(Eval("name"), Eval("StatusId"), Eval("assignfilename")) %>' />

This lets you break a complex expression up into however many lines it needs to be, which can be a little less awkward. You can use a function in your CodeBehind or any other class.

If you're binding to a class that you have access to, you could add a readonly property. Then you can do something like Eval("MyNewProperty").

I use that for exposing formatting that I need to re-use. For instance, Customer.CustomerFullName might return last name first seperated be a comma (intelligently handling situations where one or the other or both are missing) plus an optional title, since maybe my customers are medical folks and some of them have PhDs and MDs.




回答2:


I'm not really familiar with in-line codes and your code seems to be a bit complicated. But I also need to concatenate an Eval("record") and a text. So to answer the question on how to concatenate, ampersand worked for me.

'<%# Eval("name") & " *" %>'

hope this helps anyone.




回答3:


For simple one-off scenarios the code-behind function works okay.

You may also want to consider coding them as a property in the underlying object.

For example, if the text generated is going to be used in more than one instance, you'd need to code the function with Evals several times in different forms or controls.

I would create a property on the data object, e.g. NameWithStatusStar, then your label can be bound directly to the property with the code inside Eval("NameWithStatusStar")

This is more descriptive and reusable than a series of expressions, plus it's easier to change (e.g. add another field, change the formula etc.)




回答4:


You can do it like this:

Text='<%#"CustomText "+Eval("Name")%>'



回答5:


Text='<%#String.Concat(Eval("UserId"), Eval("Username")) %>'

This worked for me in my project. Found it here:

Concatenate text with Eval




回答6:


 Text='<%# string.Concat(Eval("FirstName"), " ", Eval("LastName"))%>'

This worked for me in my project. Found it here:

Concatenate text with Eval



来源:https://stackoverflow.com/questions/7668947/concatenate-two-or-more-strings-in-inline-code-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!