1

I've the following code for a DropDownListFor and is working ok

@Html.DropDownListFor(Function(model) model.Habilitacoes, New SelectList(ViewBag.Habilitacoes, "KeyHL", "DescricaoHL"), New With {.class = "FillHSpace"})

The ViewBag.Habilitacoes is a List(Of T)

But know I want to add the SelectedValue to the DropDownListFor, so I've used the following code but doesn't work.

@Html.DropDownListFor(Function(model) model.Habilitacoes, New SelectList(ViewBag.Habilitacoes, "KeyHL", "DescricaoHL", model.Habilitacoes), New With {.class = "FillHSpace"})

How can I declare the SelectedValue?

1
  • I'd use a property (e.g. SelectedHabilitaco - whatever that is ;) ) on the model. And use it as the first parameter of DropDownListFor - like in this answer: stackoverflow.com/questions/3386998/… (see Update 2). Commented May 30, 2012 at 14:29

2 Answers 2

2

You should not use the same property as first and second argument of the DropDownListFor helper. The first argument is a scalar property and the second a collection:

@Html.DropDownListFor(Function(model) model.SelectedHabilitacoes, New SelectList(ViewBag.Habilitacoes, "KeyHL", "DescricaoHL"), New With {.class = "FillHSpace"})

and then in your controller:

model.SelectedHabilitacoes = "123"
Sign up to request clarification or add additional context in comments.

Comments

0

DropdownListFor has overloads to accomplish this

DropDownListFor([SelectedValue], [SelectList], optional HTML Attributes)

Normally you would go

DropDownListFor(model => model.ID, (SelectList)ViewsBag.MySelectList, optional HTML Attributes)

The selected value will be automatically bound to the dropdown list, and will automatically be posted the the model.ID value

if this doesn't help id ask you to post your model.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.