Hi Team
I am trying to use this control on asp.net mvc, its throwing this error " System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCountryId'.'
- @Html.DropDownListFor(m=>m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new {@class = "form-control"})
- /** Controler**/
- // 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);
- }
- private List
LoadData() - {
- List
lst = new List (); - 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;
- }
- // List for countries.
- private IEnumerable
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;
- }
- // Model.cs
- public class EditTrainingRegFormViewModel
- {
- public string Title { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Position { get; set; }
- public string Company { get; set; }
- public string Address { get; set; }
- [Display(Name = "Choose country")]
- public int ? SelectedCountryId { get; set; }
- public string Code { get; set; }
- public string City { get; set; }
- public string State { get; set; }
- public string Cell_Number { get; set; }
- public List<string> Dietary_requirement { get; set; }
- public string Email { get; set; }
- public int Country_Id { get; set; }
- public string Country_Name { get; set; }
- }
Jignesh KumarPosted Mar 17, 2020, 10:12 AM