Mvc-3 Dropdownlist Or Dropdownlistfor - Can't Save Values In Controller Post
I searches for hours (or days) and didn't find a solution yet. I want to edit a customer with a DropdownListFor for the salutation with the right preselected value. I've got 3 enti
Solution 1:
You need to have Selected property in your list.
I can show you my working example:
publicstatic IEnumerable<SelectListItem> GetCountries(short? selectedValue)
{
List<SelectListItem> _countries = new List<SelectListItem>();
_countries.Add(new SelectListItem() { Text = "Select country...", Value = "0", Selected = selectedValue == 0 });
foreach (var country in ObjectFactory.GetInstance<DataRepository>().GetCountries())
{
_countries.Add(new SelectListItem()
{
Text = country.Name,
Value = country.ID.ToString(),
Selected = selectedValue > 0 && selectedValue.Equals(country.ID)
});
}
return _countries;
}
In controller i store this into viewbag:
ViewBag.Countries = CompanyModel.GetCountries(0);
In view:
@Html.DropDownListFor(m => m.CompanyModel.CountryId, (IEnumerable<SelectListItem>)ViewBag.Countries)
Post a Comment for "Mvc-3 Dropdownlist Or Dropdownlistfor - Can't Save Values In Controller Post"