我是初学者。我正在处理此ASP.NET Core MVC
项目,我正在尝试通过提交ViewModel
将POST
传递给form
方法,以便我可以将数据保存在{{} 1}}。我的Database
方法完成后,我会看到以下GET
:
RuntimeBinderException:无法将类型'System.Collections.Generic.List'隐式转换为'System.Collections.Generic.IEnumerable'。存在显式转换(您是否错过了演员?
查看:
RuntimeBinderException
控制器:
<div class="row">
<div class="col-sm-4">
<div class="input-group fg-float">
<div class="fg-line form-chose">
<label asp-for="LocationName" class="fg-labels" for="locationName"></label>
<select asp-for="LocationName" asp-items="ViewBag.Locations" class="chosen disabledropdowncntrl" data-placeholder="Choose a Location" name="locationName" id="dropDownLocationNames">
<option value=""></option>
</select>
</div>
</div>
</div>
</div>
视图模型:
// GET: ~/Inventory/Locate/Id
public IActionResult Locate(int Id)
{
InventoryLocationsHistoryViewModel locationsHistoryVM = new InventoryLocationsHistoryViewModel();
// Populating Locations DropDownList
var locationsList = new List<InventoryLocations>();
locationsList = _context.InventoryLocations.ToList();
var locations = locationsList.OrderBy(l => l.LocationName).Select(us => new SelectListItem { Value = us.LocationId.ToString(), Text = us.LocationName }).ToList();
ViewBag.Locations = locationsList;
...
...
return View(locationsHistoryVM);
}
我做错了什么?
答案 0 :(得分:0)
您错误地设置了ViewBag.Locations。您还可以折叠大量代码,因为您将整个列表放入内存以排序和选择2列。这将创建一个select语句,该语句仅选择所需的2列,并在sql server端执行排序。
// GET: ~/Inventory/Locate/Id
public IActionResult Locate(int Id)
{
InventoryLocationsHistoryViewModel locationsHistoryVM = new InventoryLocationsHistoryViewModel();
var locations = new SelectList(_context.InventoryLocations.OrderBy(l => l.LocationName)
.ToDictionary(us => us.LocationId, us => us.LocationName), "Key", "Value");
ViewBag.Locations = locations;
...
...
return View(locationsHistoryVM);
}