Search code examples
c#htmlajaxasp.net-mvcdropdownlistfor

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


I am doing an MVC APP. For this example..

In my definition of my DropDownListFor I defined something like this.

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

My Model is loaded in the Controller, where it loads Model.System under certain circumstances. Model.System is of type List<SelectListItem>

The option selected is in model.SelectedSystem that is a string type. That works fine...

The problem i am facing is when Model.System is null.

My Controller looks like this

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

On running appears the message The ViewData item that has the key SelectedSystemOrigin is of type System.String but must be of type IEnumerable<SelectListItem>

How can I draw an empty DropDownListFor without having that mistake


Solution

  • try this

    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);
    }