Populate @html.DropDownListFor() with items in Twitter Bootstrap style and C#

Gman16 picture Gman16 · Nov 27, 2013 · Viewed 9.4k times · Source

I am trying to populate a drop down list of items. I am using MVC4 with the twitter bootstrap styling, on visual studio 2012.

The code that I have for the controller is:

String[] genders =  { "Male","Female","Other"};
ViewBag.genders = new SelectList(genders);

And in my view is:

@Html.DropDownListFor("genders", "Select a gender", new { @class = "form-control" })

However, I get an error:

'The type arguments for method 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable, object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.'

I have tried various other forms of the statement. But basically I would like to keep the controller as is and edit the statements in the view. But I am open to anything which people are willing to suggest that will help me solve this issue.

Thanks in advance

Answer

cederlof picture cederlof · Nov 27, 2013

Try this:

@Html.DropDownListFor(m=>m.SelectedGender, (SelectList)ViewBag.genders, "Select gender", new { @class = "form-control" })

m=>m.SelectedGender, is where you bind the value to something in your view's model (or if you have no model, you should use @Html.DropDownList supplying a string instead).