HI everybody,
I try to populate the data from database in a dropdownlist, like this:
ViewModel:
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:
[HttpPost]
public ActionResult Create(Climb ModelViewClimb)
{
try
{
if (ModelState.IsValid)
{
db.Climbs.Add(ModelViewClimb);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (RetryLimitExceededException )
{
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:
<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:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'country.country_name'.
Thank you