I have the following model:
public class PersonListModel
{
....
[Required(ErrorMessage=AppConstants.MustSelectRecordToAttachMessage)]
public String SelectedPersonId { get; set; }
}
and the following view:
@using (Html.BeginForm("Attach", "Person", FormMethod.Post, new { @id = attachRecordFormId, targetDivId = personListId, @class = "inlineForm" }))
{
.....
@Html.HiddenFor(x => x.SelectedPersonId);
.....
<br />@Html.ValidationMessageFor(x => x.SelectedPersonId)
}
The hidden SelectedPersonId field is populated via some javascript hooked to the keyup event of one of the elements on my page.
My problem is that the required validation message shows immediately this partial view is displayed, not just when the form is submitted. It also displays again after the partial view is rendered again via an Ajax post.
I have very similar views that do not exhibit this problem, but 2 views (including the one above) that do exhibit this problem. I have been through a process of elimination to try to work out what is different between the views that work correctly and the 2 that exhibit this incorrect behavior, however I have not been able to locate the cause of the problem.
I presume that something is causing the unobtrusive validation to fire when the problem views are loaded. How can I track this down?
This could happen if the controller action that is displaying the view (containing the partial) takes the view model as argument:
The reason for this happening is because your action is taking a model => the default model binder is kicking in attempting to populate your view model and when it attempts to set a value for the
SelectedPersonIdproperty it will automatically add a validation error to the model state if there’s no corresponding value in the request because your model property is decorated with the[Required]attribute.That’s normal and could happen if the target POST action is taking your view model as argument and rendering a partial: