MVC VB.NET动态构建SelectListItem / DropDownListFor

时间:2016-06-23 16:30:08

标签: asp.net-mvc vb.net

这是我的模特:

Public Class subjectListModel 
    Public Property selectedActivity As String
    Public Property activities As IEnumerable(Of SelectListItem)
End Class

以下是我的观点:

@Html.DropDownListFor(Function(x) x.selectedActivity, Model.activities, New With {.onchange = "this.form.submit();"})

这是我的控制器:

Function populateList()

        'this is hardcoded at present, because I haven't been able to 
        'dynamically add to this IEnumerable. The implication is, I need a 
        'code change every time I add a new subject to my app ...


        Dim model = New subjectListModel With {
        .activities = {
                New SelectListItem() With {.Value = activityList(0), .Text = activityList(0)},
                New SelectListItem() With {.Value = activityList(1), .Text = activityList(1)},
                New SelectListItem() With {.Value = activityList(2), .Text = activityList(2)},
                New SelectListItem() With {.Value = activityList(3), .Text = activityList(3)},
                New SelectListItem() With {.Value = activityList(4), .Text = activityList(4)},
                New SelectListItem() With {.Value = activityList(5), .Text = activityList(5)},
                New SelectListItem() With {.Value = activityList(6), .Text = activityList(6)},
                New SelectListItem() With {.Value = activityList(7), .Text = activityList(7)},
                New SelectListItem() With {.Value = activityList(8), .Text = activityList(8)},
                New SelectListItem() With {.Value = activityList(9), .Text = activityList(9)}
            }
        }

        Return View(model)
    End Function

这很好用,并显示一个包含前十个选项的下拉列表。我想要展示更多。我已经看过通过从我的字符串数组中动态添加项目然后尝试将其转换为IEnumerable来构建列表。我花了几个小时现在看C#代码似乎做我想要的,但尽管经过多次尝试,我仍然无法在VB中使用它。问题的一个重要部分是我并不真正理解这些东西。任何帮助将不胜感激!

这是我尝试创建循环的一种方式:

Dim dropDown = New List(Of SelectListItem)
For j = 0 To 100
        dropDown.Add(New SelectListItem With {.Text = activityList(j), .Value = activityList(j)})
Next j

然后我试图将其转换为IEnumerable。

这是我尝试创建循环的另一种方式:

Dim model = New subjectListModel
For j = 0 To 100
    model.activities(New SelectListItem With {.Text = activityList(j), .Value = activityList(j)})
Next j

“太多参数”的错误

1 个答案:

答案 0 :(得分:1)

您的第一个循环(分配到Dim dropDown = New List(Of SelectListItem))会创建IEnumerable(Of SelectListItem),因此您只需使用subjectListModel将其分配给model.activities = dropDown

或者,您可以使用LINQ查询

model.activities = activityList.Select(Function(x) New SelectListItem() 
    With { .Text = x, .Value = x })

如果您只想要前100个项目,请添加.Take(100)