1

我对此进行了一些研究,但没有找到完全处理类似情况或 MVC3 的答案。在我使用的 ViewModel 中,我有一个单独模型的列表(List<AgentId>这是模型的列表AgentId)。

Create此控制器的页面中,我需要将 5 个项目的输入部分添加到此列表中。但是,在页面加载之前,我收到此错误消息:

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

这是我正在使用的 ViewModel:

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>
4

2 回答 2

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)

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

于 2013-03-20T03:18:07.993 回答
1

这个错误最终被抛出,因为ViewBag我使用的元素与列表项属性之一具有相同的名称。

解决方案是更改ViewBag.StateCodeViewBag.StateCodeList.

于 2013-03-20T16:05:00.983 回答