MVC Populating Dropdown from Database

StevieB

New to MVC trying to populate a dropdown from Database, proving a bit more tricky than I imagined.

Here's what I have.

public class EmployeeDetailsModel
{
    public string SelectedEmployee { get; set; }
    public IEnumerable<SelectListItem> Employees { get; set; }
}

Controller

public ActionResult MiEmployeeDetails()
{
  var model = new EmployeeDetailsModel();
  model.Employees = _db.geo_employees.ToList().Select(x => new SelectListItem
   {
      Value = x.name,
      Text = x.name
   });

   return View(model);
}

View

<%= Html.DropDownListFor(x => x.SelectedEmployee, (SelectList) Model.Employees) %>

But getting the error

CS1963: An expression tree may not contain a dynamic operation

Andrei

You should not cast your IEnumerable to the SelectList - you need to create a new instance of it:

<%= Html.DropDownListFor(x => x.SelectedEmployee, new SelectList(Model.Employees)) %>

Update. While the comment above holds, the actual problem turned out to be dynamically typed view. Such views do not allow use of lambdas in helpers, such as x => x.SelectedEmployee in question. So the actual solution to the problem was making view strogly typed:

Inherits="System.Web.Mvc.ViewPage<Namespace.EmployeeDetailsModel>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Populating a DropDown Menu From a MySQL Database Using Hibernate in Spring MVC

populating a dropdown from data in the database

Populating data from MySQL Database to DropDown in flutter

Populating a Bootstrap dropdown from an MS SQL Database

Populating HTML Select dropdown from a database in Meteor

Populating a page with data from a database in mvc 5

Populating dropdown with database entries

MVC - @Html.Dropdown not populating values from ViewBag

Populating a dropdown box from a database without reloading the page

Dropdown not populating from MySQL

Populating Second Dropdown Based on first dropdown from the database table without using javascript

Populating JTree from database

Populating the dropdown from the controller method

Populating dropdown list from json

Populating Dropdown with a CSV File using MVC

Populating dropdown menu with JSON Data in Mvc views

Populating dropdown from SQL Server with ajax in C# and ASP.NET MVC

populating TextWatcher from database (sqlite)

Populating RecyclerView from firebase database

Populating a list view with from a Database

Populating a ViewModel from a database model

Populating the data from ajax response into an dropdown

Dropdown list is not populating from items collection

Populating dropdown dynamically from list with Jinja

Populating a dropdown list from data table

Populating dropdown menu in separate div from php

Populating dropdown menu - selected option from server

Flutter populating data in DropDown from firebase

Populating a dropdown list with values from a text file