Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI everybody,

I try to populate the data from database in a dropdownlist, like this:

ViewModel:

C#
public class ClimbViewModel
    {
        public int Id { get; set; }

        [Required(ErrorMessage="You need to give it a name")]
        public string Name { get; set; }
        private readonly List<Country> _Country;

        public int SelectedValue { get; set; }
        public virtual Country  country { get; set; }

        public int SelectedCountryId { get; set; }
       
        public IEnumerable<SelectListItem> CountryItems
        {
            get { return new SelectList(_Country, "Id", "country_name"); }
        }

        [DisplayName("Country")]
        public virtual ICollection<Country> Countries { get; set; }

    }
}


Action method:
C#
[HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult Create(Climb ModelViewClimb)
        {
            //var CountryName = db.countries.Select .GetProductCategory(productViewModel.SelectedValue);
            try
            {
                if (ModelState.IsValid)
                {
                    //Climb climbModel = db.Climbs.Where(x => x.climbID == climb.Id).First();
                    //db.Entry(climb).State = EntityState.Modified;
                    db.Climbs.Add(ModelViewClimb);
                    
                    
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (RetryLimitExceededException /* dex */)
            {
               
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
            }
          
            ViewBag.CountryID = new SelectList(db.countries, "CountryID", "Name", ModelViewClimb.CountryID);
            return View(new ClimbViewModel() );
        }


and the view:

C#
<div class="form-group">
           <label class="control-label col-md-2" for="CountryID">Country</label>
           <div class="col-md-10">
               @Html.DropDownListFor(model => model.country.country_name, (SelectList)ViewBag.CountryID))
               @Html.ValidationMessageFor(model => model.Id)
           </div>
       </div>


But every time I get this error:
C#
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'country.country_name'.


Thank you
Posted

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