This problem has been driving me crazy and Monday mornings don’t really help.
I’m loading 2 dropdownboxes like so:
-
This one gets its selectedvalue affected by the db value
<dd><%= Html.DropDownList("type", New SelectList(ViewData("typeList"), "value", "text", Model.type), New With {.class = ""})%></dd> -
This one ignores the value loaded in the model and always displays the first value in the dropdownbox
<dd><%= Html.DropDownList("action", New SelectList(ViewData("actionList"), "value", "text", Model.action), New With {.class = ""})%></dd>
I’ve already debugged this page and Model.Action comes loaded with the correct values but they never get assigned to the selectedvalue.
EDIT:
This is the ActionResult which displays the page:
<Authorize()> _
Public Function Edit(ByVal id As Guid) As ActionResult
Dim article As Article_Ad = articleAdRepository.GetById(id)
ViewData("actionList") = GetActionValues()
ViewData("typeList") = GetTypeValues()
Return View(article)
End Function
And these are the functions which feed the dropdownboxes:
Private Function GetTypeValues() As IEnumerable(Of SelectListItem)
Dim list As New List(Of SelectListItem)
Dim sel As SelectListItem
'Imagem
sel = New SelectListItem
sel.Text = "Imagem"
sel.Value = "image"
list.Add(sel)
'Video
sel = New SelectListItem
sel.Text = "Video"
sel.Value = "video"
list.Add(sel)
Return list
End Function
Private Function GetActionValues() As IEnumerable(Of SelectListItem)
Dim list As New List(Of SelectListItem)
Dim sel As SelectListItem
' Call browser window
sel = New SelectListItem
sel.Text = "Mostrar Janela"
sel.Value = 1
list.Add(sel)
' Play fullscreen video
sel = New SelectListItem
sel.Text = "Mostrar Video em FullScreen"
sel.Value = 2
list.Add(sel)
' Show fullscreen picture
sel = New SelectListItem
sel.Text = "Mostrar Imagem em FullScreen"
sel.Value = 3
list.Add(sel)
Return list
End Function
I found out the answer to this question and I feel slightly ashamed for the final result, to be honest.
It seems that I was using the name “action” in a ViewData variable which made it conflict with the dropdownbox’s name “action”.
After changing the ViewData to “actions” (added the “s”) it stopped doing conflict and assigned the selectedvalue correctly.
My tip to anyone running into the same problem as me is to make sure there’s no other control making use of the same name you are assigning to your object, just to be on the safe side.
Thanks to everyone for the pointers here.