DataAnnotations manages client side validation issue

I am trying to get what, in my opinion, is a simple example of using DataAnnotations on a model to validate client-side validation.

Here is my model ...

public class Person { [Required(ErrorMessage = "First Name Required")] public string FirstName { get; set; } [Required(ErrorMessage = "Last Name Required")] public string LastName { get; set; } } 

Here is my controller ...

  public class FriendsController : Controller { public ActionResult Create() { Person newFriend = new Person(); return View(newFriend); } [HttpPost] public ActionResult Create(Person friendToCreate) { if (ModelState.IsValid) { // todo -- do something here return Redirect("/"); } // Invalid - redisplay form with errors return View(friendToCreate); } } 

and here is my opinion ...

 @model MvcApplication4.Models.Person <!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.js")" type="text/javascript"></script> </head> <body> <h2> Create</h2> @{Html.EnableClientValidation();} @using (Html.BeginForm()) { <fieldset> <p> @Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName) @Html.ValidationMessageFor(m => m.FirstName) </p> <p> @Html.LabelFor(m => m.LastName) @Html.TextBoxFor(m => m.LastName) @Html.ValidationMessageFor(m => m.LastName) </p> <p> <input type="submit" value="Create" /> </p> </fieldset> } </body> </html> 

Server-side validation works very well, and validation error messages are displayed as expected. However, I do not receive client-side validation confirmation. Is there something obvious that I'm missing to do a client-side check?

0
validation asp.net-mvc asp.net-mvc-3 data-annotations
Dec 19 '10 at 23:47
source share
1 answer

Have you enabled client-side validation in the web.config file?

You can do this directly in the web.config file by adding a couple of flags inside the appSetting section

 <configuration> <appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/> </appSettings> </configuration> 

or you can do it using pure c # code

 HtmlHelper.ClientValidationEnabled = true; HtmlHelper.UnobtrusiveJavaScriptEnabled = true; 

I recommend that you read Brad Wilson's article Unobtrusive Client Validation in ASP.NET MVC 3

+1
Dec 20 2018-10-12T00:
source share



All Articles