Populating a Select list in MVC 4 from code-behind

I wanted to populate a list of states on my home page in an MVC project. So I opened my HomeController.cs class and added this function:

        private static List<SelectListItem> PopulateStates()
        {
            List<string> states = new List<string>() { “AL”, “AK”, “AZ”, “AR”, “CA”, “CO”, “CT”, “DE”, “DC”, “FL”, “GA”, “HI”, “ID”, “IL”, “IN”,
                “IA”, “KS”, “KY”, “LA”, “ME”, “MD”, “MA”, “MI”, “MN”, “MS”, “MO”, “MT”, “NE”, “NV”, “NH”, “NJ”, “NM”, “NY”, “NC”, “ND”, “OH”,
                “OK”, “OR”, “PA”, “RI”, “SC”, “SD”, “TN”, “TX”, “UT”, “VT”, “VA”, “WA”, “WV”, “WI”, “WY” };
            var final = from s in states
                        select new SelectListItem
                        {
                            Text = s
                        };
            return final.ToList();
        }

As you see, I’m populating a list of SelectListItem classes, and then converting them to a List<SelectListItem > .

Still in HomeController.cs, I modified the Index method to populate the ViewData object with the List returned from the method:

        public ActionResult Index()
        {
            ViewData["States"] = PopulateStates();
            return View();
        }

And in my Index.cshtml method, I use that ViewData object to populate a DropDownList, which is done using  Html.DropDownList:

@Html.DropDownList(“ddlStates”,(IEnumerable<SelectListItem>)ViewData["States"])

About these ads
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: