2013-03-19 57 views
1

我已经研究了这一点,但没有找到相当类似的情况或MVC3的答案。在我使用的ViewModel中,我有一个单独模型的列表(List<AgentId>,它是AgentId模型的列表)。ASP MVC3错误 - 没有类型为'IEnumerable <SelectListItem>'的ViewData项目,其中包含密钥

在这个控制器的Create页面中,我需要一个输入部分来添加5个项目到这个列表。然而,之前的页面,甚至加载,我收到此错误信息:

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'BankListAgentId[0].StateCode'.

这里是视图模型我使用:

public class BankListViewModel 
{ 
    public int ID { get; set; } 
    public string ContentTypeID1 { get; set; } 
    public string CreatedBy { get; set; } 
    public string MANonresBizNY { get; set; } 
    public string LastChangeOperator { get; set; } 
    public Nullable<System.DateTime> LastChangeDate { get; set; } 

    public List<BankListAgentId> BankListAgentId { get; set; } 
    public List<BankListStateCode> BankListStateCode { get; set; } 
} 

,这里是这是使用的问题的看法的部分:

<fieldset> 
    <legend>Stat(s) Fixed</legend> 
    <table> 
    <th>State Code</th> 
    <th>Agent ID</th> 
    <th></th> 
     <tr> 
     <td> 
      @Html.DropDownListFor(model => model.BankListAgentId[0].StateCode, 
      (SelectList)ViewBag.StateCode, " ") 
     </td> 
     <td> 
      @Html.EditorFor(model => model.BankListAgentId[0].AgentId) 
      @Html.ValidationMessageFor(model => model.BankListAgentId[0].AgentId) 
     </td> 
     </tr> 
     <tr> 
     <td> 
      @Html.DropDownListFor(model => model.BankListAgentId[1].StateCode, 
      (SelectList)ViewBag.StateCode, " ") 
     </td> 
     <td> 
      @Html.EditorFor(model => model.BankListAgentId[1].AgentId) 
      @Html.ValidationMessageFor(model => model.BankListAgentId[1].AgentId) 
     </td> 
     <td id="plus2" class="more" onclick="MoreCompanies('3');">+</td> 
     </tr> 
    </table> 
</fieldset> 
+0

根据错误语句“ViewBag.StateCode”丢失。你有没有定义“ViewBag.StateCode”在操作返回视图 – Satpal 2013-03-20 06:21:41

回答

1

由于我使用的ViewBag元素与列表项属性之一具有相同的名称,所以抛出此错误时抛出错误。

解决方案是将ViewBag.StateCode更改为ViewBag.StateCodeList

2

我相信@Html.DropDownListFor()期待一个IEnumerable<SelectListItem>,你可以将它绑定方式如下:

在您的视图模型:

public class BankListViewModel 
{ 
    public string StateCode { get; set; } 

    [Display(Name = "State Code")] 
    public IEnumerable<SelectListItem> BankListStateCode { get; set; } 

    // ... other properties here 
} 

在控制器中加载数据:

[HttpGet] 
public ActionResult Create() 
{ 
    var model = new BankListViewModel() 
    { 
     // load the values from a datasource of your choice, this one here is manual ... 
     BankListStateCode = new List<SelectListItem> 
     { 
      new SelectListItem 
      { 
       Selected = false, 
       Text ="Oh well...", 
       Value="1" 
      } 
     } 
    }; 

    return View("Create", model); 
} 

然后在视图将其绑定:

@Html.LabelFor(model => model.BankListStateCode) 
@Html.DropDownListFor(model => model.StateCode, Model.BankListStateCode) 

我希望这有助于。如果你需要澄清,请告诉我。

+0

我试图使用列表输入,所以它应该是空白时,视图呈现。也许我需要在控制器中初始化它? – NealR 2013-03-20 15:24:18

相关问题