So I have an MVC application in which I'm trying to display a list of items in a ListBox, allowing the user to add or remove items as needed. Here's what's happening:
This is my Get, in which I create the SelectList to show in the ListBox in the View:
' GET: Trucks/Edit/5
Async Function Edit(ByVal id As Integer?) As Task(Of ActionResult)
....
Dim curItems As SelectList
If truck.Items IsNot Nothing Then
curItems = New SelectList(truck.Items, "ID", "Name")
Else
curItems = New SelectList("")
End If
ViewData("ItemNames") = curItems
Return View(truck)
End Function
So then this is my Edit View:
@ModelType myproject.Truck
@Code
ViewData("Title") = "Edit"
Dim ItemNames As SelectList
ItemNames = ViewData("ItemNames")
End Code
<h2>Edit Truck</h2>
@Using (Html.BeginForm("Edit", "Trucks", FormMethod.Post, New With {.name = "frmTruckEdit", .id = "frmTruckEdit"}))
@Html.AntiForgeryToken()
@<div class="form-horizontal">
<hr />
<div class="text-danger">@(ViewData("TError"))</div>
@Html.ValidationSummary(True, "", New With {.class = "text-danger"})
@Html.HiddenFor(Function(model) model.ID)
<br />
....
<div class="form-group">
<div class="control-label col-md-2" style="font-weight: bold">Items for this Truck</div>
<div class="col-md-10">
@Html.ListBox("ItemNames", New SelectList(ItemNames), htmlAttributes:=New With {.id = "ItemNames", .class = "mylistbox"})
</div>
<div class="col-md-offset-2 col-md-10">
<br />
<div class="btn-link" id="RemoveItem">Remove Selected Item</div>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div> End Using
So trying it this way, where I specify New SelectList(ItemNames) in the ListBox arguments, the items in the ListBox show as "System.Web.Mvc.SelectListItem".
If I simply remove the "New SelectList" so that argument is just ItemNames, the items in the ListBox show correctly (the name text), however, when I hit Post, I get error
There is no ViewData item of type 'IEnumerable< SelectListItem >' that has the key 'ItemNames'
Note: I also tried using it as an IEnumerable(Of SelectListItem) instead. 'New' can't be used with that so I can't try specifying "New IEnumerable(ItemNames)" in the ListBox, and just "ItemNames" gives me the same error about no ViewData item.
I am at a loss right now as to what I'm doing wrong here. Let me know if you need more info. Thank you!!