This ASP.NET Core 7/Razor page project uses JQuery Validation and Unobtrusive Validation. The page concerned has a [Required] text input field and 2 dropdown lists (these are not marked [Required]). The lists are populated with the rest of the model on page GET. Each field can be edited and the dropdown values changed as expected.
When I force a validation fail by removing the text in the mandatory field the expected error message is displayed - BUT the 2 dropdown lists have lost all their values and have reverted to the default text. No postback occurs, which is I believe correct behaviour on failed validation, but the html has changed.
Html before validation failure:
<div class="form-group">
<label class="form-label" for="engagement_CoachingModelId">Coaching model</label>
<select class="form-control" aria-required="true" id="engagement_CoachingModelId" name="engagement.CoachingModelId">
<option value="">Please select coaching model</option>
<option value="0">None</option>
<option selected="selected" value="1">Model 1</option>
<option value="3">Model 3</option>
<option value="4">Model 4</option>
</select>
</div>
Html after validation failure:
<div class="form-group">
<label class="form-label" for="engagement_CoachingModelId">Coaching model</label>
<select class="form-control" aria-required="true" id="engagement_CoachingModelId" name="engagement.CoachingModelId">
<option value="">Please select coaching model</option>
</select>
</div>
What am I missing here?
There were two things I was doing wrong:
Firstly, the
<partial name="_ValidationScriptsPartial" />
tag was before the jquery script tag in the layout file. I could have seen this by checking console errors. Not sure why but I was still getting the initial validation error message but it was then doing a postback but...
Secondly, the on post method in the code behind had the wrong name so it WAS posting back but my method wasn't catching it.
Fixing these 2 mistakes fixed the problem. Hope this is of some use to someone else one day.