Ray
Ray

Reputation: 4947

Select Tag Helper renders an empty list when getting data from viewmodel

I'm trying to get the select tag helper to list items from my view model property but it is always empty when I rendered on the browser:

The view model has:

public int AssetTypeId { get; set; }
public List<SelectListItem> AssetTypes { get; set; }

My controller has this:

    [HttpGet("details/{id}")]
    public async Task<IActionResult> Details(string id)
    {

        var asset = await _assetRepository.GetByIdAsync(id);
        var vm = _mapper.Map<Asset, AssetViewModel>(asset);            
        var assetTypes = await _assetTypeRepository.ListAsync();
        vm.AssetTypes = assetTypes.Select(x => new SelectListItem()
        {
            Value = x.Id.ToString(),
            Text = x.AssetTypeName
        }).ToList();            

        return View(vm);
    }

When I put a breakpoint on the last line, I see the 3 items in the AssetTypes property.

My view has:

<select id="AssetTypeId" asp-for="AssetTypeId" asp-items="@Model.AssetTypes">
    <option>Please select one</option>
</select>

Even when I put a breakpoint on this line in my view, I again see the 3 items that should appear. But when viewing in the browser, the select tag gets rendered as:

<select id="AssetTypeId" asp-for="0" asp-items="System.Collections.Generic.List`1[Microsoft.AspNetCore.Mvc.Rendering.SelectListItem]">
     <option>Please select one</option>
</select>

Clearly the rendered HTML tells me why my list is empty but I don't know how to fix this. I tried the solution from this question but keep getting the same results.

Upvotes: 1

Views: 842

Answers (1)

ChadT
ChadT

Reputation: 7693

The tag helper is not triggering at all.

In your ViewImports.cshtml file, are you including the appropriate tag helpers? E.g:

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

Upvotes: 2

Related Questions