0

我对这个 ASP.net MVC 的东西很陌生,并且真的被困在 ListBoxFor 和 DropDownListFor 上。

我该如何使用它们?有什么例子吗?

4

1 回答 1

7

这真的没那么难。与往常一样,您从定义视图模型开始:

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

然后是控制器:

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

最后是相应的强类型视图:

@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
于 2012-09-25T12:33:49.673 回答