i have some issues with default value of my dropdownlist when returning my model to view in case of one or many errors. I have a dropdownlist in the view which is filled fro
You need to populate both SelectList
's in the controller methods so they get passed to the view. In the GET method, the 2nd one will be an empty SelectList
(assuming its a 'Create' metod), but in the POST method it will be populated based on the country that has been selected.
You model should include
public class CountrydetailsViewModel
{
[Required(Error Message = "..")]
public int? SelectedCountry { get; set; }
[Required(Error Message = "..")]
public int? SelectedTown { get; set; }
....
public IEnumerable<SelectListItem> CountryList{ get; set; }
public IEnumerable<SelectListItem> TownList { get; set; }
}
And your controller methods
public ActionResult Countriesdata()
{
CountrydetailsViewModel vm = new CountrydetailsViewModel();
ConfigureViewModel(vm);
return View(vm);
}
[HttpPost]
public ActionResult Countriesdata(CountrydetailsViewModel returnmodel)
{
if(!ModelState.IsValid)
{
ConfigureViewModel(returnmodel);
return View(returnmodel);
}
.... // save and redirect
}
private ConfigureViewModel(CountrydetailsViewModel model)
{
var countries = dal.countries();
model.CountryList= countries.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.CountryID.ToString()
});
if (model.SelectedCountry.HasValue)
{
// adjust query to suit your property names
var towns = db.towns.Where(e => e.CountryId == model.SelectedCountry);
model.TownList = towns.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.TownID.ToString()
});
}
else
{
model.TownList = new SelectList(Enumerable.Empty<SelectListItem>());
}
}
This also allows you to generate the correct options and default selections when editing an existing CountrydetailsViewModel
.
Then in the view, use
@Html.DropDownListFor(m => m.SelectedCountry, Model.CountryList, "-Select a Country-", new { @class = "ddlist" })
@Html.ValidationMessageFor(m => m.SelectedCountry)
@Html.DropDownListFor(m => m.SelectedTown, Model.TownList, "-Select a Country-", new { @class = "ddlist" })
@Html.ValidationMessageFor(m => m.SelectedTown)
Note that there is no point creating an identical SelectList
from the original one you passed to the view by using new SelectList(..)
- its just unnecessary extra overhead. Note also that the last parameter in the SelectList
constructor is ignored when your binding to a model property (internally the method builds its own SelectList
based on the value of the property) - you could put whatever value you wanted as the last parameter and you will see that the option is still correct selected based on the value of the property.