I must be doing something wrong here but I can't find an easy way to get this to work.
Imagine the following code:
<asp:RadioButtonList ID="MyRadioButtonList" runat="server">
<asp:ListItem Value="<%= CompanyName.SystemName.Constants.PaymentFrequency.FREQUENT.ToString() %>" Text="Yes" Selected="True"></asp:ListItem>
<asp:ListItem Value="<%= CompanyName.SystemName.Constants.PaymentFrequency.ONCE.ToString() %>" Text="No, Just do this once"></asp:ListItem>
</asp:RadioButtonList>
But it doesn't compile the statement before it renders the page. So if I get the selected value of this radiobuttonlist it contains something like "<%= Compan... %>" instead of what my constant defines.
What is the correct syntax for this?
I don't know why exactly (I didn't manage to find a reference) but the <%= %>
syntax doesn't work when you are setting the Value or the Text of a ListItem, in ASPX mark-up.
You could instead do it from code-behind, like:
MyRadioButtonList.Items.Add(new ListItem(
"Yes", CompanyName.SystemName.Constants.PaymentFrequency.FREQUENT.ToString()));
//...
If you really want the constants in markup (not in code behind per the accepted answer), since ASP.NET 2.0 this can be done with a custom ExpressionBuilder.
First, create an ExpressionBuilder class in your web application:
namespace Your.Namespace
{
[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context)
{
return new CodeSnippetExpression(entry.Expression);
}
}
}
Then register it in your web.config:
<compilation debug="true">
<expressionBuilders>
<add expressionPrefix="Code" type="Your.Namespace.CodeExpressionBuilder"/>
</expressionBuilders>
</compilation>
Finally, call it in your markup using the <%$ %>
syntax:
<asp:RadioButtonList ID="MyRadioButtonList" runat="server">
<asp:ListItem Value="<%$ Code: CompanyName.SystemName.Constants.PaymentFrequency.FREQUENT.ToString() %>" Text="Yes" Selected="True"></asp:ListItem>
<asp:ListItem Value="<%$ Code: CompanyName.SystemName.Constants.PaymentFrequency.ONCE.ToString() %>" Text="No, Just do this once"></asp:ListItem>
</asp:RadioButtonList>
I got most of the code from here:
http://weblogs.asp.net/infinitiesloop/The-CodeExpressionBuilder
MSDN ASP.NET Expressions Overview
https://msdn.microsoft.com/en-us/library/d5bd1tad.aspx
MSDN ExpressionBuilder Class Reference
https://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder(v=vs.110).aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With