Click here to Skip to main content
15,441,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Team

I am using DropDownlistFor in order to get all the list of available countries in the world. Now i am getting this exception saying there is no ViewData item of IEnumerable. This type is only created on my controller, do i need to create it on my Model class.

What I have tried:

private IEnumerable<SelectListItem> GetCountryList()
  {
      SelectList listcn = null;
      try
      {
          var list = this.LoadData().Select(p => new SelectListItem
          {
              Value = p.Country_Id.ToString(),
              Text = p.Country_Name
          });
          listcn = new SelectList(list, "Value", "Text");

      }catch(Exception ex)
      {
         // throw ex;
      }
      return listcn;
  }


   private List<EditTrainingRegFormViewModel> LoadData()
{
    List<EditTrainingRegFormViewModel> lst = new List<EditTrainingRegFormViewModel>();

    try
    {
        string line = string.Empty;
        string srcFilePath = "Content/files/country_list.txt";
        var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
        var fullPath = Path.Combine(rootPath, srcFilePath);
        string filePath =  new Uri(fullPath).LocalPath;
        StreamReader src = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));

        // while to read the file
        while((line = src.ReadLine()) !=null) {
          EditTrainingRegFormViewModel infoLst = new EditTrainingRegFormViewModel();
            string[] info = line.Split(',');

            //Setting
            infoLst.Country_Id = Convert.ToInt32(info[0].ToString());
            infoLst.Country_Name = info[1].ToString();

            lst.Add(infoLst);
        }
        src.Dispose();
        src.Close();
    }catch(Exception ex)
    {
        Console.Write(ex);
    }
    return lst;
}


// Selection for countries in the world.

      public ActionResult DropDownSelect()
      {
          EditTrainingRegFormViewModel model = new EditTrainingRegFormViewModel();

          model.SelectedCountryId = 0;

          this.ViewBag.CountryList = this.GetCountryList();
          return this. View(model);
      }


@Html.DropDownListFor(m=>m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new {@class = "form-control"})
Posted
Updated 17-Mar-20 4:23am

1 solution

Look at the types involved:

ViewBag.CountryList is assigned to the value returned by GetCountryList().

GetCountryList returns a IEnumerable<SelectListItem>.

Your view attempts to cast ViewBag.CountryList to a SelectList using the as operator. This will return null, because the value isn't a SelectList. There is no conversion between IEnumerable<SelectListItem> and SelectList.

Change your view to specify the correct type, and use a cast instead of as so you'll get a better error message if the cast fails:
Razor
@Html.DropDownListFor(m => m.SelectedCountryId, (IEnumerable<SelectListItem>)ViewBag.CountryList, new { @class = "form-control" })
Type-testing and cast operators - C# reference | Microsoft Docs[^]
SelectList Class (System.Web.Mvc) | Microsoft Docs[^]
SelectExtensions.DropDownListFor Method (System.Web.Mvc.Html) | Microsoft Docs[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900