I have a view model that looks like this:
public class VenueIndexViewModel : BaseViewModel { public VenueAddViewModel Venue; ... } public class VenueAddViewModel { ... [Required(ErrorMessage = "This field is required")] public string State { get; set; } ... }
In my opinion, I provide a form with a drop-down list for this property, for example:
using (var form = Html.BeginForm()) { ... @Html.DropDownListFor(x => x.Venue.State, Model.GetStates()) @Html.ValidationMessageFor(x => x.Venue.State) ... }
This works, but the problem is that the Required attribute in the view model is ignored. If I look at the HTML, the data-val- * attributes are also missing.
<select id="Venue_State" name="Venue.State">...</select>
However, if I changed the rendering to a text box ...
using (var form = Html.BeginForm()) { ... @Html.TextBoxFor(x => x.Venue.State) @Html.ValidationMessageFor(x => x.Venue.State) ... }
I see the expected data-val- * attributes and the validation work:
<input data-val="true" data-val-required="This field is required" id="Venue_State" name="Venue.State" type="text" value="">
I should note that I have other view models elsewhere that use DropDownListFor with a model with a flat view (without nested objects), and the check works correctly there, so I think I got an error in handling MVC check for dropdowns Lists when using a nested view model. Can anyone confirm / advise?
Chris source share