2013-03-19 56 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

相關問題