0
votes

In my cshtml view I have this pre-made (scaffold) code that I changed a little to be able to put a list of enums down there instead of a textbox:

 <div class="form-group">
                <label asp-for="Color" class="control-label"></label>
                <select asp-for="Color" asp-items="Model.Colors" class="form-control"></select> 
                <span asp-validation-for="Color" class="text-danger"></span>
  </div>

Error occurs at Model.Colors.

And in my model I tried doing: Colors.Add(new List<SelectListItem>()); as told in Cannot implicitly convert type 'System.Web.Mvc.SelectList' to 'System.Collections.Generic.ICollection<System.Web.Mvc.SelectList>', but than I would get a different error; Cannot implicitly convert 'System.Collections.Generic.List' to 'System.Web.Mvc.SelectListItem'.

Even though Colors is a List<SelectListItem>.

But before that I had this in the ViewModel:

public EnumsDTO.Color Color { get; set; }
public List<SelectListItem> Colors { get; set; }
public void AddColorViewModel()
{
    Colors = new List<SelectListItem>();
    foreach (Color c in (Color[])Enum.GetValues(typeof(Color)))
    {
        Colors.Add(new SelectListItem
        {
            Value = ((int)c).ToString(),
            Text = c.ToString()
        });
    }
}

I was trying to follow this tutorial: https://www.youtube.com/watch?v=MPJ9PPCWxoI

1
Please provide a reproducible example, this code isnt clear thus its hard to see exactly what the problem is. - Kieran Devlin
obviously wrong using at the top of the file - Selvin
@KieranDevlin I was following this tutorial, but to show all code is a little too much because they have nothing to do with this. But it basically goes wrong when the guy in the tutorial tries to get de method to the cshtml-file with asp-items = Model.etc - Zheng-rong Cai
@Selvin What using should I have? - Zheng-rong Cai

1 Answers

0
votes

You are most likely using System.Web.Mvc namespace in your model at the top of the file. While SelectListItem exists there, the one that is expected in the view is from the Microsoft.AspNetCore.Mvc.Rendering namespace.

Therefore, there are 2 ways to resolve the issue:

Option 1

  1. Get rid of using System.Web.Mvc;
  2. Add using Microsoft.AspNetCore.Mvc.Rendering;

Option 2

  1. Change the relevant occurrences of SelectListItem in your model to Microsoft.AspNetCore.Mvc.Rendering.SelectListItem