2010-12-19 67 views
0

我试图得到什么,我认为是使用一个模型DataAnnotations来驱动客户端验证,以及一个简单的例子。DataAnnotations驾驶客户端验证问题

这里是我的模型......

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

这里是我的控制器......

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); 
    } 
} 

,这里是我的观点...

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

服务器端验证工作正常,验证错误消息按预期显示。但是,我没有得到客户端验证的工作。有什么显而易见的,我失踪,使客户端验证出现?

回答

1

您是否在您的web.config文件上启用了客户端验证?

您可以直接做在web.config文件添加几个标志的appSetting部分

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

,或者您可以使用纯C#代码

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

做到这一点,我建议你的内心阅读Brad Wilson的文章Unobtrusive Client Validation in ASP.NET MVC 3

+0

感谢您的快速回答。我刚刚阅读了布拉德的文章,感谢您的链接。他描述了我遇到的确切问题。 原来,如果我从上面删除了MS脚本,而是包含了jquery.validate.js和jquery.validate.unobtrusive.js,那么客户端验证工作得很好!对于MVC3来说,MS特定的东西似乎让位于JSON实现。很高兴看到MS正在朝这个方向发展,而不是尝试自己吃掉整个苹果。 – 2010-12-20 00:16:26

+0

不客气。很高兴帮助! – Lorenzo 2010-12-20 00:17:37