I have a View with a ViewModel.
It has a form that posts back a completely different Model.
I am try to get Client Validation working.
I have
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
My view looks like so:
<form method="post" action="@Url.Action("Checkout")">
@Html.ValidationSummary()
<table>
<tr>
<td>Forename:</td>
<td>@Html.TextBox("Forename") @Html.ValidationMessage("Forename","*")</td>
</tr>
</table>
</form>
I get the impression that Client Validation creates HTML5 attributes based on the ViewModel on the inputs but I dont have that ViewModel for it to create data attributes so how can client validation work?
The way client validation works out of the box is that it uses the ModelMetadata of the view model passed to the view to emit HTML5
data-*attributes on the input fields based on Data Annotation attributes you have used on your view model. If you are using a completely different view model as action argument in your POST action this obviously won’t work as server side validation will rely upon the view model in the POST action while client validation will rely upon the view model passed to the view rendering this form.The only solution I can see to this problem is to forget about automatic client validation and define the jquery.validate rules manually so that they are coherent with the view model you are using in the POST action on the server. So you can basically forget about the
data-*attributes, exclude thejquery.validate.unobtrusive.min.jsscript from your page and get into coding: