我有一个mvc 3 vb.net应用程序,我需要生成几个viewbags ...我尝试以下代码只是在每个循环后在viewbag名称的末尾删除一个变量,但它不会采取它..它表示“对象变量或未设置块变量”。当它是第二次传递时的viewbag.status(p)线时,它通过循环......
Dim p As Integer = 0
For Each registrant In b
Dim _regi As attendance = registrant
Dim _status As New List(Of String)
If Not String.IsNullOrWhiteSpace(_regi.Completed_Class) Then
_status.Add(_regi.Completed_Class)
End If
_status.Add("--")
_status.Add("Absent")
_status.Add("Left Early")
_status.Add("Completed")
ViewBag._status(p) = _status
p = p + 1
Next
视图如下:
@ModelTYPE List(Of xxxxxx.attendance)
@Code
ViewData("Title") = "Class Attendance Record"
End Code
@Using Html.BeginForm
@<fieldset>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Registrant ID</th>
<th>Course Status</th>
<th>Comments</th>
</tr>
@For r As Integer = 0 To Model.Count - 1
Dim i As Integer = r
@Html.HiddenFor(Function(m) m(i).id)
@Html.HiddenFor(Function(m) m(i).course_ref)
@<tr>
<td>@Html.DisplayFor(Function(m) m(i).firstName)
@Html.HiddenFor(Function(m) m(i).firstName)
</td>
<td>@Html.DisplayFor(Function(m) m(i).lastName)
@Html.HiddenFor(Function(m) m(i).lastName)
</td>
<td>@Html.DisplayFor(Function(m) m(i).reg_id)
@Html.HiddenFor(Function(m) m(i).reg_id)
</td>
<td>@Html.DropDownListFor(Function(m) m(i).Completed_Class, New SelectList(ViewBag._status(i)))
@Html.HiddenFor(Function(m) m(i).Completed_Class)
</td>
<td>@Html.TextBoxFor(Function(m) m(i).Comments, New With {.class = "AttenComment"})
@Html.HiddenFor(Function(m) m(i).Comments)
</td>
</tr>
Next
</table>
<p><input type="submit" name="submit" /></p>
</fieldset>
End Using
任何想法???
答案 0 :(得分:0)
根据您提供的代码,ViewBag._status
实际上持有List(Of List(Of String))
。换句话说,每个`ViewBag._status(p)实际上都是一个List(Of String),而_status本身就是一个列表或数组。
我认为解决问题的方法是先完成所有工作,然后在循环结束后设置ViewBag._status
。
Dim statusLists As New List(Of List(Of String))
For Each registrant In b
Dim _regi As attendance = registrant
Dim _status As New List(Of String)
If Not String.IsNullOrWhiteSpace(_regi.Completed_Class) Then
status.Add(_regi.Completed_Class)
End If
_status.Add("--")
_status.Add("Absent")
_status.Add("Left Early")
_status.Add("Completed")
statusLists.Add(_status)
Next
ViewBag._status = statusLists
答案 1 :(得分:0)
我只是在我的视图的每个循环中创建了viewbag ...所以这样每次它通过循环来处理表中的每个项目时它都会为下拉列表生成项目视图包..