将DropDownList SelectList转换为List<> [英] Convert DropDownList SelectList to List<>
问题描述
新SelectList出错:无法将SelectList转换为List<>
Error on new SelectList: "Can not convert SelectList to List<>"
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
Class1.cs
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
Index.cshtml
@model DropDownList2.Models.listclass
@Html.DropDownList("ddl0", new SelectList(Model.list, "ID", "Name"))
推荐答案
tables.list = new SelectList
list属性是List< Table>并且您将其设置为SelectList。 SelectList不是List< Table>所以这是行不通的。 Google提供了如何使用下拉列表和使用MVC的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.
您的属性类型为列表< Table1>
。
您正在尝试将其设置为SelectList
类型的值。
这是两种完全不同的类型,它们之间没有隐式转换。
更改代码以将属性设置为正确的值类型:
Your property is of typeList<Table1>
.
You are trying to set it to a value of typeSelectList
.
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:
tables.list = new List<Table1>
{
new Table1 { ID = "1", Name = "name1" },
new Table1 { ID = "2", Name = "name2" },
new Table1 { ID = "3", Name = "name3" },
};
如果你不明白为什么你不能将一种类型的值赋给不同类型的属性,那么你需要阅读一些基本的C#教程。
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.
这篇关于将DropDownList SelectList转换为List<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!