我正在尝试创建一个下拉列表,但它给了我一个错误,提示“无法将类型‘string’隐式转换为‘System.Web.Mvc.SelectList’。我的代码如下:
应用程序数据库模型:
public string dropdown{ get; set; }
应用程序 View 模型:
public SelectList dropdown{ get; set; }
应用服务.cs:
public static SelectList GetDropdownList(string currSelection)
{
List<SelectListItem> list = new List<SelectListItem>();
list.Add(new SelectListItem { Value = "1", Text = "firstvalue" });
list.Add(new SelectListItem { Value = "2", Text = "secondvalure" });
list.Add(new SelectListItem { Value = "3", Text = "All of the Above" });
return new SelectList(list, "Value", "Text", currSelection);
}
在我的 Controller 中我调用:
applicationviewmodel.dropdown= ApplicationService.GetDropdownList(null);
and then trying to save it in database as:
ApplicationDatabaseModel.dropdown= applicationviewmodel.dropdown;
这是我得到这个错误的地方。
在我看来我有:
@Html.DropDownListFor(x => x.dropdown, applicationviewmodel.dropdown)
我不确定如何进行这项工作。
最佳答案
我发现将列表作为模型的一部分并使用简单的 linq 语句会更容易。以下国家/地区下拉列表的简单示例:
假设你有一个像这样的模型
public class MyModel()
{
public int CountryId { get; set; }
public List<Country> Countries { get; set; }
}
和一个 Country 类
public class Country()
{
public int Id { get; set; }
public string Name { get; set; }
}
在您看来,您可以执行以下操作:
@Html.DropDownListFor(m => m.CountryId,
Model.Countries.Select(x =>
new SelectListItem { Text = x.Name, Value = x.Id.ToString(), Selected = Model.CountryId == x.Id }, "Please Select...", null)
关于c# - 在 MVC5 中创建下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562413/