I want to validate values in DropDownListFor but its not working. I have included required script files for client side validation too.
In ViewModel:
public class SearchViewModel
{
public List<MarriageProfile> Profiles { get; set; }
public SearchProfile SearchProfile { get; set; }
}
public class SearchProfile
{
[Required(ErrorMessage="*")]
public SelectList Ages { get; set; }
public string Age { get; set; }
}
In Controller:
var ages = AgeList
.Select(p => new SelectListItem()
{
Text = p.ToString(),
Value = p.ToString()
}).ToList();
SearchViewModel.SearchProfile.Ages = new SelectList(ages, "Text", "Value");
static List<string> AgeList = new List<string>()
{
"18-23",
"23-28",
"28-33",
"33-38",
"38-43",
"43-48"
};
In View:
@Html.DropDownListFor(model => model.Age, Model.Ages, "--Select One--", new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Age)
On submitting the form, no client or server side validation is working for the dropdownlist above. What could be wrong with the code?
It appears you need to tag the
Age
property with theRequired
attribute and not theAges
list. Check out this answer: ASP.NET MVC 3 and validation attribute for dropdownlist with default value of 0