在MVC5中创建下拉列表

时间:2014-05-09 10:33:12

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

我正在尝试创建一个下拉列表,但它给出了一个错误,说'不能隐式转换类型'字符串'到'System.Web.Mvc.SelectList'。我的代码如下:

应用程序数据库模型:

public string dropdown{ get; set; }

应用程序视图模型:

public SelectList dropdown{ get; set; }

ApplicationService.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);
    }

在我的控制器中我打电话:

 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)

我不确定如何使这项工作。

2 个答案:

答案 0 :(得分:2)

我发现将List作为模型的一部分并使用简单的linq语句会更容易。以下是一个国家/地区下拉的简单示例:

假设你有一个类似

的模型
public class MyModel()
{
    public int CountryId { get; set; }
    public List<Country> Countries { get; set; }
}

和国家类

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)

答案 1 :(得分:0)

此:

@Html.DropDownListFor(x => x.dropdown, applicationviewmodel.dropdown)

..不正确。它正在尝试将所选项目存储到SelectList实例中。

您想要的是视图模型上的string变量,该值被选择为:

public class ApplicationViewModel {
    public SelectList DropDown { get; set; }
    public string SelectedDropDownValue { get; set; }
    // .. the rest of the properties here
}

然后你的观点就变成了这个:

@Html.DropDownListFor(x => x.SelectedDropDownValue, Model.DropDown)

这表示“将所选值存储到SelectedDropDownValue”。

然后,您需要更改SelectList的构建方式。 Value是发布到您的媒体资源的内容。Text是浏览器中显示的内容。

所以这个:

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" });

..必须是这样的:

list.Add(new SelectListItem { Value = "firstvalue", Text = "firstvalue" });
list.Add(new SelectListItem { Value = "secondvalue", Text = "secondvalure" });
list.Add(new SelectListItem { Value = "all of the above", Text = "All of the Above" });

..因为它们是字符串(除非你希望要回发的数字)。

然后,最后,您的控制器代码变为:

// assign the string value to the string property
ApplicationDatabaseModel.dropdown = applicationviewmodel.SelectedDropDownValue;