tonyedwardspz tonyedwardspz - 2 months ago 22
ASP.NET (C#) Question

Adding SelectListItem to SelectList

I have a MVC app using the Entity framework. I have two entities, user and faculty.

I'm trying to add the faculties to a select list for a dropdown box used during the editing of a user. I'm getting the error:

"Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Web.Mvc.SelectList'"

I googled around and been through a few solutions to similar questions on here but had no luck.

EditUserModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Purely_Servers.Models
{
public class EditUserModel
{
public user User { get; set; }
public SelectList FacultyList { get; set; }
}
}


usersController

public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}


var model = new EditUserModel
{
User = db.Users.Find(id),
FacultyList = (
from f in db.Faculties
select new SelectListItem
{
Value = f.id.ToString(),
Text = f.name
}).ToList() /////////////////////ERROR HERE
};


if (model == null)
{
return HttpNotFound();
}
return View(model);
}


Any help would be much appreciated.

Answer

When you use ToList(), the enumerable is converted to a List<SelectListItem>, which cannot be cast to a SelectList.

You have 2 options:

  1. Change the FacultyList property to be of type List<SelectListItem>.
  2. Convert the query to a SelectList (see code below).

Code for option 2:

FacultyList = new SelectList(
    from f in db.Faculties
    select new SelectListItem
    {
        Value = f.id.ToString(),
        Text = f.name
    });