0

Say in web.config, I have

<configSections>
    <section name="myOptions" type="System.Configuration.NameValueSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>

<myOptions>
    <add key="myKey1" value="myValue1">
    <add key="myKey2" value="myValue2">
    ...
</myOptions>

I want to loop through myOptions and render as HTML using the key and value fields.

<select>
    <option value="myKey1">myValue1</option>
    <option value="myKey2">myValue2</option>
    ...
</select>

From Googling, I have tried

<% var optionValuePairs = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("fundGroupOptions"); %>
<% foreach(string key in optionValuePairs) { %>
   <option value="<% key.ToString(); %>"><% optionValuePairs[key].ToString(); %></option>
<% }; %>

I can access the collection just fine. But my option value="" is blank, the option text is also blank.

Kyle
  • 5,407
  • 6
  • 32
  • 47
  • You will need some sort of looping mechanism, such as a Repeater or GridView, or possibly a plain for loop. – mason Aug 26 '15 at 15:23
  • Thanks. How can I access web.config and put the section in a key-value collection? – Kyle Aug 26 '15 at 15:28

1 Answers1

0

Figured it out... I hope this helps someone save time Googling. Web.Config needs to be formatted as above.

Then you just need to access the section as a simple NameValueCollection. You can then use foreach to render your HTML.

<% var optionValuePairs = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("myOptions"); %>
<% foreach(string key in optionValuePairs) { %>
    <option value="<% =key %>"><% =optionValuePairs[key] %></option>
<% }; %>
Kyle
  • 5,407
  • 6
  • 32
  • 47