Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

asp.net mvc populate dropdown from web.config value

  • 27-03-2012 11:04AM
    #1
    Registered Users, Registered Users 2 Posts: 872 ✭✭✭


    Hi, I have a string of types in the web.config like so :
    <add key="types" value="one|two|three|four|five|six"/>
    

    I would like to populate a dropdown with these values and then use an integer for the value. I am confused how i can autoset an integer for each entry .

    Desired output
    <select id="types">
    	<option selected="selected" value="0">one</option>
    	<option value="1">two</option>
    	<option value="2">three</option>
    	<option value="3">four</option>
    	<option value="4">five</option>
    	<option value="5">six</option>
    </select>
    

    I was thinking of using a dictionary but am unsure how to set the value field (the ??? below). Could i use some sort of enumeration for this ?
    public IEnumerable<SelectListItem> ReportTypes
            {
                get { return new SelectList(getReportList());}
            }
    
            public Dictionary<int,String> getReportList()
            {
                String reportTypes = ConfigurationManager.AppSettings["types"].ToString();
    
                Dictionary<int, String> types = new Dictionary<int, string>([B]???[/B],reportTypes.Split('|'));
    
                return types;
            }
    

    Thanks for any tips


Comments

  • Registered Users, Registered Users 2 Posts: 12,036 ✭✭✭✭Giblet


    You could do something like this
    <add key="types" value="1,one|2,two|3,three|4,four|5,five|6,six"/>
    
    And split on "|" then split on ","

    You can also use a loop for add each key to the dictionary using an incrementing index.

    You could also hook up a configuration section and have a class which holds the structure which can be de-serialised from the web.config.


  • Registered Users, Registered Users 2 Posts: 1,311 ✭✭✭Procasinator


    Sounds like the job of a for loop to me. Or if you like LINQ:
    public IEnumerable<SelectListItem> GetReportList()
    {
    	string reportTypes = ConfigurationManager.AppSettings["types"].ToString();
    	return reportTypes.Split('|')
    		.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
    }
    

    The only thing I would say, why do you need a numeric value? Could you not use the text as the the value, too.

    You could run into a problems if you were storing the chosen values somewhere and wanted to add an item somewhere in between values. Your generated indexes would then no longer match up.


Advertisement
Advertisement