This article is about MVC 2, which used MicrosoftAjax. MVC 4 no longer includes MS Ajax files as they are deprecated, and using jquery is the preferred method.
To check your settings, make sure these scripts are in your layout.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
And these two parameters are present in the appSettings section in the web.config file
<add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
Therefore, when you add data annotations to your ViewModels, you get confirmation on the client side and on the server side as
public class MyModel { [Required] [StringLength(30)] public string FirstName { get; set; } [Required] [StringLength(30)] public string LastName { get; set; } }
In your opinion, just make sure you have such code
<div> @Html.LabelFor(model => model.FirstName) </div> <div> @Html.TextBoxFor(model => model.FirstName) <br/> @Html.ValidationMessageFor(model => model.FirstName) </div> <div> @Html.LabelFor(model => model.LastName) </div> <div> @Html.TextBoxFor(model => model.LastName) <br/> @Html.ValidationMessageFor(model => model.LastName) </div>
Update
Here is an example of a custom validator that I called RateRequiredIfCustomIndexRate This is the javascript side to add to the jquery validation
$("document").ready(function () { var isCustomRateRequired = document.getElementById("IsCustomRateRequired"); isCustomRateRequired.onchange = function () { if (this.checked) { $('#Rate').attr('disabled', 'disabled'); $('#Rate').val(''); } else { $('#Rate').removeAttr('disabled'); } }; }); jQuery.validator.addMethod("raterequiredifcustomindexrate", function (value, element, param) { var rateRequired = $("#CustomRateRequired").val(); if (rateRequired && value == "") { return false; } return true; }); jQuery.validator.unobtrusive.adapters.addBool("raterequiredifcustomindexrate");