I am populating a dropdownlist in mvc using viewbag. i want to set a default value to this dropdownlist, if the page is not saved with any other value. Otherwise the selected item should be the one they select and save the page.
this is how i populate my viewbag
ViewBag.ListOfCountries = new SelectList(Db.Countries, "CountryCode", "CountryName");
this is the view side:
<%: Html.DropDownListFor(m => m.OfficeAddressCountry, (IEnumerable<SelectListItem>)ViewBag.ListOfCountries, new{@class="required"}) %>
If you want to pass default value for the dropdown list than you can do is pass default viewmodel/model with default value
Example :
or you can try this
You have to use different overlaod of DropDownListFor. Consider this:
Now it will set default selected option to "Default Selected Option" if the model property
OfficeAddressCountry
contains no value.You can check this fiddle for default value and this with selected option which is in Model