MVC 加载错误 HTML。具有键 'MY KEY' 的 ViewData 项目是 'System.String' 类型,但必须是 'IEnumerable<SelectListItem>' 类型

The MVC error on load HTML. ViewData item that has the key 'MY KEY' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'

我正在做一个MVC APP。对于这个例子..

在我的 DropDownListFor 定义中,我定义了这样的东西。

  @Html.DropDownListFor(model => model.SelectedSystem, Model.Systems, new { @class = "form-control listbox",id="Origin" })

我的模型加载到控制器中,它在某些情况下加载 Model.System。 Model.System 的类型是 List<SelectListItem>

选择的选项在 model.SelectedSystem 中,即 string type。效果很好...

我面临的问题是 Model.System 为 null。

我的控制器看起来像这样

public ActionResult Index()
        {
            var apiEntitySyncViewModel = new ApiEntitySyncViewModel
            {
                Systems = _entitySyncService.GetEnvironments(),
            };
            return View(apiEntitySyncViewModel);
        }

在 运行 上出现消息 The ViewData item that has the key SelectedSystemOrigin is of type System.String but must be of type IEnumerable<SelectListItem>

我怎样才能画一个空的 DropDownListFor 而不会出现那个错误

试试这个

public ActionResult Index()
{
   var apiEntitySyncViewModel = new ApiEntitySyncViewModel
   {
       Systems = _entitySyncService.GetEnvironments(),
  };
if(apiEntitySyncViewModel.Systems==null) apiEntitySyncViewModel.Systems = new List <SelectListItem>();

//or you can try
new List <SelectListItem>{ new SelectListItem{ Value="0", Text ="Empty" } 


  return View(apiEntitySyncViewModel);
}