我试图得到我认为是在模型上使用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>
服务器端验证工作正常,验证错误消息按预期显示。但是,我没有让客户端验证工作。是否有一些显而易见的东西可以让客户端验证出现?
答案 0 :(得分: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