Click here to Skip to main content
15,893,381 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Error on new SelectList: "Can not convert SelectList to List<>"
C#
listclass tables = new listclass();
public ActionResult Index()
{
    tables.list = new SelectList(new[] {
                    new {ID="1",Name="name1"},
                    new{ID="2",Name="name2"},
                    new{ID="3",Name="name3"},
                },
                "ID", "Name", 1);
    return View(tables);
}

Class1.cs
SQL
namespace DropDownList2.Models
{
    public class Table1
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
    }
    public class listclass
    {
        public List<Table1> list { get; set; }
    }
}

Index.cshtml
SQL
@model DropDownList2.Models.listclass


@Html.DropDownList("ddl0", new SelectList(Model.list, "ID", "Name"))
Posted
Updated 6-Oct-15 5:17am
v5
Comments
Krunal Rohit 6-Oct-15 9:51am    
Can you share your listclass code ?

-KR
Richard Deeming 6-Oct-15 10:03am    
We cannot see your screen, access your computer, or read your mind.

If you don't post the definition of your listclass class, we can't help you.

tables.list = new SelectList


The "list" property is List<Table> and you are setting it to SelectList. SelectList isn't List<Table> so that won't work. Google for examples of how to use dropdowns and SelectList with MVC.
 
Share this answer
 
Your property is of type List<Table1>.

You are trying to set it to a value of type SelectList.

Those are two completely different types, and there is no implicit conversion between them.

Change your code to set the property to a value of the correct type:
C#
tables.list = new List<Table1>
{
    new Table1 { ID = "1", Name = "name1" },
    new Table1 { ID = "2", Name = "name2" },
    new Table1 { ID = "3", Name = "name3" },
};


If you don't understand why you can't assign a value of one type to a property of a different type, then you need to read some basic C# tutorials.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900