In my viewModel I have
public string Addressline1 { get; set; }
public List<SelectListItem> StateList
{
get
{
return State.GetAllStates().Select(state => new SelectListItem { Selected = false, Text = state.Value, Value = state.Value }).ToList();
}
}
In the view I have
@Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
when AddressLine1 is entered, then the statelist DropDownList selection is Required.How do I validate and show an error message when no state is selected in the Drop down list other than default "select" value?
Decorate your
StateCode
property with the[Required]
attribute:and then you could add a corresponding validation error message:
UPDATE:
Alright it seems that you want to conditionally validate this
StateCode
property depending on some other property on your view model. Now that's an entirely different story and you should have explained this in your original question. Anyway, one possibility is to write a custom validation attribute:and now decorate your
StateCode
property with this attribute, like so:Now assuming you have the following form:
the
StateCode
dropdown will be required only if the user entered a value into theAddressLine1
field.