C# ASP MVC 2:POST上的dropdownlist出现错误
好的,我是asp mvc2的新手,我遇到了一些问题 htmlhelper调用Html.dropdownlistfor() 我想向用户显示一周中的天数列表。我希望所选项目绑定到我的模型 我创建了这个小类来生成一个天数列表+一个简短的符号,我将使用它存储在数据库中C# ASP MVC 2:POST上的dropdownlist出现错误,c#,asp.net,asp.net-mvc,post,drop-down-menu,C#,Asp.net,Asp.net Mvc,Post,Drop Down Menu,好的,我是asp mvc2的新手,我遇到了一些问题 htmlhelper调用Html.dropdownlistfor() 我想向用户显示一周中的天数列表。我希望所选项目绑定到我的模型 我创建了这个小类来生成一个天数列表+一个简短的符号,我将使用它存储在数据库中 public static class days { public static List<Day> getDayList() { List<Day> daylist = new L
public static class days
{
public static List<Day> getDayList()
{
List<Day> daylist = new List<Day>();
daylist.Add(new Day("Monday", "MO"));
daylist.Add(new Day("Tuesday", "TU"));
// I left the other days out
return daylist;
}
public class Dag{
public string DayName{ get; set; }
public string DayShortName { get; set; }
public Dag(string name, string shortname)
{
this.DayName= name;
this.DayShortName = shortname;
}
}
}
我的模型里有这条线
public string ChosenDay { get; set; }
在我的视图中显示以下列表:
<div class="editor-field">
<%: Html.DropDownListFor(model => model.ChosenDay, ViewData["days"] as SelectList, "--choose Day--")%>
</div>
然后我将抛出以下异常:
The ViewData item that has the key 'ChosenDay' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.
键为'ChosenDay'的ViewData项的类型为'System.String',但必须为'IEnumerable'类型。
此错误会在视图中显示下拉列表的行中抛出
我真的不知道如何解决这个问题,我在网上找到了几种解决方案。但它们都没有真正起作用
提前准备 我见过这样的错误。
这是因为当呈现视图时,SelectList为空时,ViewData[“days”]。这可能是因为ViewData[“days”]为空或为其他类型,然后选择List。
必须在此处找到问题:
[HttpPost]
public ActionResult Registreer(EventRegistreerViewModel model)
{
}
使舒尔,即此代码
SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName");
ViewData["days"] = _list;
运行并确保ViewData[“days”]在返回视图之前不为null和IEnumerable。它必须是因为Model.IsValid,因此ViewData[“days”]未绑定。当HttpPost控制器操作看到“EventRegistreerViewModel”时,将调用模型构造函数 因此,如果您向EventRegistrerViewModel模型添加代码,如下所示:
...
public IEnumerable<string> MySelectList { get; set; }
public EventRegistreerViewModel() {
// build the select the list as selectList, then
this.MySelectList = selectList;
}
这样,每次构建视图模型时,它都将包括选择列表。现在我注意到了!谢谢你的帮助:D
SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName");
ViewData["days"] = _list;
[HttpPost]
public ActionResult Registreer(EventRegistreerViewModel model)
...
public IEnumerable<string> MySelectList { get; set; }
public EventRegistreerViewModel() {
// build the select the list as selectList, then
this.MySelectList = selectList;
}
Html.DropDownListFor(model => model.ChosenDay, model.MySelectList, "--choose Day--")