0

Title states what I'm trying to do.

Controller method:

public IActionResult Create()
        {
            IEnumerable<string> hList = from char s in _context.NR_Users select s.ToString();

            List < NR_User > hUsers = new List<NR_User>();
            hUsers = (from c in _context.NR_Users select c).ToList();
            hUsers.Insert(0, new NR_User { ID = 0, Name = "Select" });
            ViewBag.historyUsers = hUsers;

            List<SelectListItem> options = new()
            {
                new SelectListItem { Value = "True", Text = "Yes" },
                new SelectListItem { Value = "False", Text = "No" }
            };
            ViewBag.options = options;
            return View();
        }

View:

<div class="form-group col-md-4">
                    <label class="control-label">History PM</label>
                    <select asp-for="History_PM" name="History_PM" class="form-control" asp-items="@ViewBag.historyUsers"></select>
                    <span asp-validation-for="History_PM" class="text-danger"></span>
                </div>

But when I run the app and navigate to the Create page I get this error:

RuntimeBinderException: Cannot implicitly convert type 'System.Collections.Generic.List<EnvApp.Models.DB.NR_User>' to 'System.Collections.Generic.IEnumerable<Microsoft.AspNetCore.Mvc.Rendering.SelectListItem>'. An explicit conversion exists (are you missing a cast?)

I understand that it can't implicitly convert the list to an IEnumerable, but how exactly do I do that?

1 Answer 1

3

You can convert the list using SelectList class.

Try replacing

<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="@ViewBag.historyUsers"></select>

with

<select asp-for="History_PM" name="History_PM" class="form-control" asp-items="@(new SelectList(ViewBag.historyUsers, "ID", "Name"))"></select>
Sign up to request clarification or add additional context in comments.

1 Comment

That did it, thank you a ton man I had no idea!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.