When I populate a DropDownList with data in the View .aspx my validation styles are applied when I submit without selecting from Country DropDownList.
In my web model I have this:
[DisplayName("Country")]
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "ListingPost_FK_Country_CodeRequired", ErrorMessageResourceType = typeof(ErrorMessages))]
public string Country { get; set; }
In my View is this:
Html.DropDownList("Country", new[] {
new SelectListItem { Text = "US", Value = "US" },
new SelectListItem { Text = "Canada", Value = "CA" },
new SelectListItem { Text = "Outside US/Canada", Value = "-1" }, },
"Please Select")
If I submit without picking a country my DropDownList get a red border and all is well.
But when I populate the DropDownList in code I lose the validation (red border) with no country picked. The ModelState.IsValid is false but why am I losing client validation style?
IQueryable countries = null;
using (MyEntities context = new MyEntities())
{
countries = from country in context.Countries
select country;
List countryList = countries.OrderBy(c => c.Description).ToList();
Country countryDefault = countryList.FirstOrDefault(c => c.Country_Code == "US");
ViewData["Country"] = new SelectList(countryList, "Country_Code", "Description", countryDefault);
}
Also, my default Country object is not being set. When populating in C#, it's defaulting to the first item in list and should be defaulting to US.
Thanks...