仅当modelstate无效时才会发生MVC视图异常

时间:2014-10-13 08:30:07

标签: validation asp.net-mvc-5 html.dropdownlistfor modelstate asp.net-mvc-views

我正在编写MVC 5互联网应用程序,当我的模型未验证时,正在报告错误。

这是我的创建视图中的错误,如下所示:

  

发生了'System.InvalidOperationException'类型的异常   System.Web.Mvc.dll但未在用户代码中处理

     

附加信息:具有密钥的ViewData项   'assetCategory'的类型为'System.String',但必须是type   '的IEnumerable'。

在这行代码中:

@Html.DropDownListFor(m => m.assetCategory, Model.assetCategories, htmlAttributes: new { @class = "form-control" })

以下是相关字段:

public IEnumerable<SelectListItem> assetCategories { get; set; }
public string assetCategory { get; set; }

以下是完整的群组代码:

<div class="form-group">
    @Html.LabelFor(model => model.assetCategory, null, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.assetCategory, Model.assetCategories, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.assetCategory, "", new { @class = "text-danger" })
    </div>
</div>

仅当模型未验证时才会发生此错误。如果模型确实验证,则不会发生错误,并填充下拉列表,我可以检索assetCategory字符串中的选定值。

我可以帮忙看一下这段代码吗?

1 个答案:

答案 0 :(得分:0)

确保您没有将Model.assetCategories传递为null,您必须确保为该属性加载数据,否则此错误将抛出。