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

标签 c# asp.net asp.net-mvc post drop-down-menu

好的,我是 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/

相关文章:

asp.net-mvc - 如何将 ASP.NET MVC View 呈现为字符串?

c# - .net mysql 连接器与 odbc mysql 连接器 3.51

c# - ASP.NET 5 在 Startup 类中的ConfigureServices 中访问上下文或请求信息

asp.net - jQuery ajax 调用的返回值的大小限制是多少?

javascript - ASP.NET MVC 中的 Kendo Treemap 工具提示

c# - 单元测试应用程序_开始

javascript - 在 JavaScript 中迭代 IEnumerable 模型

c# - ASCII字符转换为C#中的十六进制值

C# 使用 SHA1 将字符串散列为字节数组

c# - 以编程方式在 asp.net 中调用回发