c# - 在 MVC5 中创建下拉列表

标签 c# view asp.net-mvc-5 html.dropdownlistfor

我正在尝试创建一个下拉列表,但它给了我一个错误,提示“无法将类型‘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/

相关文章:

c# - 将参数传递到 Xamarin Forms 行为

mysql - MySQL 中查询 View 的速度

java - 自定义ViewPager

c# - 路径的 Controller ...未找到或未实现 IController

jquery - 如何强制我的 Html.DropDownlist 根据其内容长度具有灵活的大小

c# - linq to entities 的 linq 更新问题

c# - 如何从 C# 调用 Java 代码?

objective-c - Objective-C 有观点吗?

asp.net-mvc - 如何更改 MVC 5 中的 url?

c# - 如何在 Unity 中使用 Serilog?