VB.NET - Using ListBoxFor and DropDownList

Che Letton picture Che Letton · Sep 25, 2012 · Viewed 8.8k times · Source

Im new to this ASP.net MVC stuff and getting really stuck on ListBoxFor and DropDownListFor.

How do I use them? Any examples?

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 25, 2012

It's really not that hard. As always you start by defining a view model:

Public Class MyViewModel
    Public Property SelectedItems As IEnumerable(Of String)
    Public Property SelectedItem As String
    Public Property Items As IEnumerable(Of SelectListItem)
End Class

then a controller:

Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Function Index() As ActionResult
        Dim model = New MyViewModel 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(model)
    End Function

    Function Index(model As MyViewModel) As ActionResult
        ' Here you can use the model.SelectedItem which will
        ' return you the id of the selected item from the DropDown and 
        ' model.SelectedItems which will return you the list of ids of
        ' the selected items in the ListBox.
        ...
    End Function
End Class

and finally a corresponding strongly typed view:

@ModelType MvcApplication1.MyViewModel

@Using Html.BeginForm()
    @Html.DropDownListFor(Function(x) x.SelectedItem, Model.Items)
    @Html.ListBoxFor(Function(x) x.SelectedItems, Model.Items)
    @<input type="submit" value="OK" />
End Using