gpt4 book ai didi

c# - ASP MVC 2 : Error with dropdownlist on POST

转载 作者:太空宇宙 更新时间:2023-11-03 11:48:31 25 4
gpt4 key购买 nike

好的,我是 asp mvc2 的新手,我遇到了一些问题htmlhelper 调用 Html.dropdownlistfor();

我想向用户显示一周中的几天列表。我希望所选项目绑定(bind)到我的模型。

我创建了这个小类来生成天数列表和一个简短的符号,我将使用它来将其存储在数据库中。

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

我现在真的知道这是否是正确的方法

然后我把它放在我的 Controller 中:

SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName");
ViewData["days"] = _list;
return View("");

我的模型中有这条线

public string ChosenDay { get; set; }

我认为这是显示列表:

<div class="editor-field">
<%: Html.DropDownListFor(model => model.ChosenDay, ViewData["days"] as SelectList, "--choose Day--")%>
</div>

现在这一切都很完美。在第一次访问时,但是当我做一个 [HttpPost]如下所示:

[HttpPost]
public ActionResult Registreer(EventRegistreerViewModel model)
{
// I removed some unrelated code here

// The code below executes when modelstate.isvalid == false
SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName");
ViewData["days"] = _list;
return View(model);
}

然后我将抛出以下异常:

The ViewData item that has the key 'ChosenDay' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'.

这个错误是在我显示下拉列表的那一行抛出的。

我真的不知道如何解决这个问题并尝试了我在网上找到的几种解决方案。但它们都没有真正起作用。

提前联系!

最佳答案

我见过这样的错误。这是因为 ViewData["days"] as SelectList 在呈现 View 时为 null。这可能是因为 ViewData["days"] 为空或类型与 SelectList 不同。问题一定出在这里:

[HttpPost]
public ActionResult Registreer(EventRegistreerViewModel model)
{
}

确保这段代码

SelectList _list = new SelectList(Days.getDayList(), "DayShortName", "DayName");
ViewData["days"] = _list;

运行并且 ViewData["days"] 在您返回 View 之前不为 null 和 IEnumerable。一定是因为 Model.IsValid 所以 ViewData["days"] 没有绑定(bind)。

关于c# - ASP MVC 2 : Error with dropdownlist on POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2754513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com