2010-09-13 109 views
1

我正在使用MVC 2和实体框架4.在我的创建应用程序页面上,我有一个下拉列表,其中填充了我的AccountType枚举中的值。这是我做的:ASP.NET MVC 2下拉问题

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 --") %> 

页面加载,我开始输入一些数据后。我从下拉列表中选择一个值。当输入所有必需的输入时,我点击提交。下面是只是一块代码:

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

     return View(); 
     } 

然后我碰到下面的错误,不知道这意味着什么,但我没有谷歌它,尝试了样品,但我仍然得到消息。以下是错误消息:

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'AccountTypeID'. 

我甚至改变了下拉列表的视图中的:

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

我不知道我做错了吗?我将不胜感激:)

谢谢。

+0

我想应用程序类包含AccountTypeID属性?错误发生在POST上,或者是什么?问题有点模糊.. – mare 2010-09-13 14:03:00

回答

1

在您的文章的行动,你需要填写ViewData["AccountTypes"]你在你的GET动作一样的工作方式,因为你正在返回相同的观点和这一观点依赖于它:不使用的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(); 
} 

显然这个答案自带通常免责声明,当我看到有人使用的ViewData,而不是视图模型和强类型的意见,我总是做。

+0

谢谢。这是一个相当古老的帖子。当时我刚开始做MVC。我学会了不使用ViewData。 – 2011-03-09 06:18:04

1

第一:你不能有可选的值转换为枚举所以你应该在你的帖子收到一个字符串,然后做一些逻辑投给你枚举:

[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(); 
    } 

二:你的DropDownList ID必须是你的帖子动作参数的名字相同的名字:如果你把

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

那么你的行动应该有“的applicationID”参数不是“应用程序”