Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set ListItem value to constant for RadioButtonList in ASPX

Tags:

asp.net

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?

like image 770
Peter Avatar asked Sep 23 '10 11:09

Peter


2 Answers

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()));
//...
like image 179
Dan Dumitru Avatar answered Oct 14 '22 07:10

Dan Dumitru


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

like image 44
Rich Avatar answered Oct 14 '22 08:10

Rich