DataAnnotations driving client side validation iss

2019-08-27 17:50发布

问题:

I am trying to get what I think is a simple example of using DataAnnotations on a model to drive the client side validation as well.

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 view...

@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>

The server side validation works just fine and the validation error messages appear as expected. However, I am not getting the client side validation to work. Is there something obvious that I am missing to make the client side validation appear?

回答1:

Did you enabled Client side Validation on your web.config file?

You can do it directly on the web.config file 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 you read Brad Wilson's article Unobtrusive Client Validation in ASP.NET MVC 3