I can’t insert a Dropdown box in C# . Net Core, is there a type conversion error?

Asked

Viewed 23 times

1

Error:

Runtimebinderexception: Cannot implicitly Convert type 'Object' to 'System.Collections.Generic.Ienumerable<Microsoft.AspNetCore.Mvc.Rendering.Selectlistitem>'. An Explicit Conversion exists (are you Missing a cast?)

The Model:

public IEnumerable<SelectList> Emails { get; set; }

The Controller:

public IActionResult Create()
{
  var mls =
    (from geral in _context.Clientes
      orderby geral.Email
      select new { text = geral.Email, value = geral.Email }).ToList();
   ViewBag.MailList = mls.AsEnumerable();
  return View();
}

The View:

<select asp-for="Emails" asp-items="@ViewBag.MailList"></select>

The error appears in the view, if I send a null object until the empty checkbox appears. I’ve tried every kind of conversion and nothing, someone has some light?

  • Select the view code

  • 1

    view:.. <select Asp-for="Emails" Asp-items="@Viewbag.Maillist"></select>

  • 1

    I fixed it. Edudemar, the type is not as it is being sent to View

1 answer

0


The error happens because the wrong type is being sent to View, make that statement new SelectList and pass the properties as required and upon being sent to your View the type is already correct to be used.

public IActionResult Create()
{
    var mls = (
        from geral in _context.Clientes
        orderby geral.Email
        select new { text = geral.Email, value = geral.Email }
    ).ToList();

   ViewBag.MailList = new SelectList(mls, "value", "text");

   return View();
}

that is, the declaration of the right type and recognised by the code of its View.

References

  • I appreciate the attention, the controller part worked, but the view part I had to do in an alternative way... half POG, but okay, it worked. i would like to use: <select Asp-for="Name" Asp-items="@Viewbag.Maillist"></select> but he gave the list below the checkbox, I had to do the following: @{ foreach (var j in Viewbag.Maillist) { <option value="@j. Value">@j. Text</option> } } . Valeu!!!!

  • In the View No need to do anything @Eudemartonatto did so in Controller is enough

Browser other questions tagged

You are not signed in. Login or sign up in order to post.