I cannot get this ListBox to have a value. It worked in MVC4.5, from which I am translating; cannot get to work in MVC Core. Swear it was working at some point; now it is not.
Have tried: https://stackoverflow.com/a/19144613/2496266 https://stackoverflow.com/a/40308906/2496266 etc.
View
<div class="tb-field desc-field">
@Html.ListBoxFor(model => model.workerRequests,
new SelectList(ViewBag.workerRequests, "Value", "Text"),
new { id = "workerRequests2_WO-"+ Model.ID, tabindex = "22", style="min-width: 16em;"}
)
</div>
Controller (GET)
wo.workerRequests = new List<ViewModel.WorkerRequest>();
ViewData["workerRequests"] = new SelectList(wo.workerRequests);
return PartialView("Create", wo);
Controller (POST)
public async Task<ActionResult> Create(WorkOrder wo, string userName)
{
ModelState.ThrowIfInvalid();
var modelUpdated = await _adaptor.TryUpdateModelAsync(this, wo);
// ... "wo.WorkerRequests" is empty here ^
}
Entity
public virtual ICollection<WorkerRequest> workerRequests { get; set; }
Additional info:
Apparently it is coming across in the Request, but as a StringValue:
...apparently all of them are string values. It's not getting bound to its desired type.
Basically:
We are selecting the Worker in the WorkerRequest from the database (nested type). Is this due to the lazy-loading bugs? What am I doing wrong?
It looks like you are creating 2 SelectList
objects for the view.
Once in controller:
ViewData["workerRequests"] = new SelectList(wo.workerRequests);
And again in the view:
@Html.ListBoxFor(model => model.workerRequests,
new SelectList(ViewBag.workerRequests, "Value", "Text"),
You only need to create one and the best place would be in the view. So change your controller code to populate the ViewData
with the data and let the view create the SelectList
to display:
ViewData["workerRequests"] = wo.workerRequests;
Now you should see the list box populated with the data.
For the curious, this is what we ended up with:
public ActionResult Create(Domain.WorkOrder wo, string userName, List<Domain.WorkerRequest> workerRequestList)
{
UpdateModel(wo);
Domain.WorkOrder neworder = woServ.Create(wo, userName);
// JSON object with new work order data
var result = map.Map<Domain.WorkOrder, ViewModel.WorkOrder>(neworder);
return Json(new
{
sNewRef = result.tabref,
sNewLabel = result.tablabel,
iNewID = result.ID
},
JsonRequestBehavior.AllowGet);
}
<div class="tb-label desc-label">
@Html.LabelFor(model => model.workerRequests)
<br />
<input type="button" value="@Machete.Web.Resources.WorkOrder.requestAdd" class="formButton" id="addRequestBtn-@(Model.ID)"/>
<input type="button" value="@Machete.Web.Resources.WorkOrder.requestRemove" class="formButton" id="removeRequestBtn-@(Model.ID)"/>
</div>
<div class="tb-field desc-field">
@Html.ListBox("workerRequests2", new SelectList(ViewBag.workerRequests, "Value", "Text"), new { id = "workerRequests2_WO-"+ Model.ID, tabindex = "22", style="min-width: 16em;"})
</div>