Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 242
Gman16 Avatar asked Dec 03 '22 21:12

Gman16


1 Answers

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).

like image 179
cederlof Avatar answered Dec 11 '22 17:12

cederlof