Reputation: 43
This code may seem a little weird, but it is educational so I think it is acceptable:
[HttpGet]
public async Task<IActionResult> Create()
{
var residents = await _residentAccountService.GetResidentAccounts();
var viewModel = new AddRealEstateViewModel
{
Residents = residents.Select(x => x.FirstName + " " + x.FamilyName).ToList()
};
List<SelectListItem> items = new List<SelectListItem>();
foreach (string accountNames in viewModel.Residents)
{
items.Add(new SelectListItem() { Text = $"{accountNames}", Value = $"{accountNames}" });
}
SelectList selectList = new SelectList(items, "Text");
ViewBag.Zb = selectList;
ModelState.Clear();
return View("CreateRealEstateView", viewModel);
}
Inside the action I am trying to access to data about Residents through my fellow's service, and then transfer this to view as SelectListItem
for DropDownListFor
.
Here how it looks in the view:
<select asp-for="ResidentAccount" asp-items= "@Html.DropDownListFor((IEnumerable<dynamic>)Model.Residents, ViewBag.Zb, "Set the Owner", new { @class = "foo"})" class="form-control"></select>
I get this error:
RuntimeBinderException: The type arguments for method 'Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<UtopiaCity.ViewModels.HousingSystem.AddRealEstateViewModel>.DropDownListFor(System.Linq.Expressions.Expression<System.Func<UtopiaCity.ViewModels.HousingSystem.AddRealEstateViewModel,TResult>>, System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>, string, object)' cannot be inferred from the usage. Try specifying the type arguments explicitly. CallSite.Target(Closure , CallSite , IHtmlHelper , IEnumerable , object , string , <>f__AnonymousType0 ) System.Dynamic.UpdateDelegates.UpdateAndExecute5<T0, T1, T2, T3, T4, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4) AspNetCore.Views_HousingSystem_CreateRealEstateView.b__26_0() in CreateRealEstateView.cshtml + "@Html.DropDownListFor((IEnumerable)Model.Residents, ViewBag.Zb, "Set the Owner", new { @class = "foo"})" Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
I don't know what I am doing wrong there is no compile error
Upvotes: 2
Views: 176
Reputation: 43939
try this
var items = new List<SelectListItem> {Value="0", Text="Set the Owner"};
foreach (string accountNames in viewModel.Residents)
{
items.Add(new SelectListItem() { Text = $"{accountNames}", Value = $"{accountNames}" });
}
ViewBag.SelectList = items;
and view
<select asp-for="ResidentAccount" asp-items= "@ViewBag.Selectlist", new { @class = "foo"})" class="form-control"></select>
Upvotes: 0