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.
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>
<% }; %>