Asp.net mvc ASP.NET MVC 2下拉列表问题

Asp.net mvc ASP.NET MVC 2下拉列表问题,asp.net-mvc,Asp.net Mvc,我正在使用MVC2和实体框架4。在“创建应用程序”页面上,我有一个下拉列表,其中填充了AccountType枚举中的值。我就是这样做的: public ActionResult Create() { // Get the account types from the account types enum var accountTypes = from AccountType at in Enu

我正在使用MVC2和实体框架4。在“创建应用程序”页面上,我有一个下拉列表,其中填充了AccountType枚举中的值。我就是这样做的:

public ActionResult Create()
      {
         // Get the account types from the account types enum
         var accountTypes = from AccountType at
                            in Enum.GetValues(typeof(AccountType))
                            select new
                            {
                               AccountTypeID = (int)Enum.Parse(typeof(AccountType), at.ToString()),
                               AccountTypeName = GetEnumFriendlyName(at)
                            };
         ViewData["AccountTypes"] = new SelectList(accountTypes, "AccountTypeID", "AccountTypeName");

         return View();
      }
这是此下拉列表数据的代码外观:

<%= Html.DropDownList("AccountTypeID", (SelectList)ViewData["AccountTypes"], "-- Select --") %>
然后我得到了下面的错误,不确定它是什么意思,但我做了谷歌,尝试了样本,但我仍然得到了消息。以下是错误消息:

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'AccountTypeID'.
没有具有键“AccountTypeID”的“IEnumerable”类型的ViewData项。
我甚至将视图中的下拉列表更改为:

<%= Html.DropDownList("AccountTypeID", (IEnumerable<SelectListItem>)ViewData["AccountTypes"], "-- Select --") %>

我不确定我做错了什么?我希望您能提供一些意见:)

谢谢。

首先:您不能将可选值强制转换为Enum,因此您应该在帖子中收到一个字符串,然后进行逻辑转换,将其强制转换为Enum:

    [HttpPost]
    public ActionResult Create(string application)
    {
        if (ModelState.IsValid)
        {
            // Do your stuff here to convert this string to your Enum 
            // But you should take care for null string
        }

        return View();
    }
Second:您的DropDownList Id应该与Post action参数的名称相同:如果您将

<%: Html.DropDownList("applicationID", (SelectList)ViewData["AccountTypes"], "-- Select --")%>


然后,您的操作应该具有“applicationID”参数,而不是“application”

在POST操作中,您需要以与GET操作相同的方式填充
视图数据[“AccountTypes”]
,因为您返回的是相同的视图,并且此视图取决于此视图:

[HttpPost]
public ActionResult Create(Application application)
{
    if (ModelState.IsValid)
    {
        application.ApplicationState = (int)State.Applying;
    }

    ViewData["AccountTypes"] = ... // same stuff as your GET action
    return View();
}

显然,当我看到有人使用ViewData而不是视图模型和强类型视图时,我通常会做出这样的声明:不要使用ViewData,使用视图模型和强类型视图。

我想应用程序类包含AccountTypeID属性?错误发生在帖子上,还是怎么了?这个问题有点模糊,谢谢。这是一篇相当古老的文章。那是我第一次开始做MVC的时候。我已经学会了不使用ViewData。
[HttpPost]
public ActionResult Create(Application application)
{
    if (ModelState.IsValid)
    {
        application.ApplicationState = (int)State.Applying;
    }

    ViewData["AccountTypes"] = ... // same stuff as your GET action
    return View();
}