Jakub Wisniewski
Jakub Wisniewski

Reputation: 2249

Dropdownlistfor MVC ASP.Net VB

I send data to my dropdownlistfor and i can choose that data but when i click button to go to post method i get error:

"An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The ViewData item that has the key 'SelectedItem' is of type 'System.String' but must be of type 'IEnumerable'."

I thought that the first value in razor view in dropdownlistfor is the selected value and second is list of values to show but now i have no idea how the dropdown list works ;/

could you help me?

My model code:

Public Class NewProcessIndex

    Public Property Name As String
    Public Property DataSource1 As String

    Public Property SelectedItem As String
    Public Property Items As IEnumerable(Of SelectListItem)

End Class

My controller code:

<HttpGet>
Function AddNewProces() As ActionResult

    Dim listBoxData = New NewProcessIndex With {
        .Items = {
            New SelectListItem() With {.Value = 1, .Text = "item 1"},
            New SelectListItem() With {.Value = 2, .Text = "item 2"},
            New SelectListItem() With {.Value = 3, .Text = "item 3"}
        }
    }

    Return View(listBoxData)
End Function

<HttpPost>
Function AddNewProces(newProcesData As NewProcessIndex) As ActionResult

    newProcesData.DataSource1 = newProcesData.SelectedItem

    Return View(newProcesData)
End Function

And Finally my view code:

@ModelType NewProcessIndex

<h2>AddNewProces</h2>
@Using (Html.BeginForm("AddNewProces", "Admin", FormMethod.Post))

    @<div class="form-horizontal">

        @Html.LabelFor(Function(m) m.Name)
        @Html.TextBoxFor(Function(m) m.Name)
        @Html.ValidationMessageFor(Function(m) m.Name)

        @Html.DropDownListFor(Function(x) x.SelectedItem, Model.Items)

         <input type="submit" value="AddNewProces" />
    </div>

End Using

@If FormMethod.Post Then
    @<p>@Model.Name</p>
    @<p>@Model.DataSource2</p>
End If

EDIT: funny thing ... the dropdownlistfor doesn't work but listboxfor works in this form:

@Html.ListBoxFor(Function(x) x.SelectedItem, Model.Items)

Upvotes: 1

Views: 4984

Answers (1)

Jakub Wisniewski
Jakub Wisniewski

Reputation: 2249

Probably the fact that i am returning a model to the view was an issue or me having a fun with

@If isPost Then
 ...
End If

I am not sure what caused the error but now I am using ListBoxFor and everything works like it should.... strange :) If anyone still would like to explain me why it doesn't work as expected (well as i expect it to work) then answer me right away :)

Upvotes: 0

Related Questions