我有所有脚本的布局页面,如下所示。
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Site</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<some custom css>
<modernizr>
<script src="~/Scripts/Jquery/jquery-1.9.1.js"></script>
<script src="~/Scripts/Jquery/jquery-ui-1.10.2.js"></script>
<script src="~/Scripts/Jquery/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.js"></script>
<script src="~/Scripts/Jquery/jquery.validate.unobtrusive.js"></script>
<some custom scripts>
<bootstrap scripts>
<knockout scripts>
</head>
<body>
@RenderBody()
</body>
</html>
然后我有我的注册表,如图所示
@model Mysite.Models.Account.Account
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "register" }))
{
@Html.AntiForgeryToken();
<h1>Login</h1>
@Html.ValidationSummary();
@Html.EditorFor(m => m.Name)
@Html.EditorFor(m => m.Address1)
@Html.EditorFor(m => m.Address2)
@Html.EditorFor(m => m.Phone1)
<input type="button" value="Register" id="btn1" />
}
<script>
var form = $("#register");
$("#btn1").click(function (e) {
e.preventDefault();
$.ajax({
url: 'http://localhost:3885/Account/Register',
data: form.serialize(),
type: 'POST',
success: function (result) {},
error: function (req, status, error) {
function(req, status, error);
}
});
});
</script>
我的帐户模型类如下:
public class Account
{
public Name name {get; set;}
public Address Address1 {get; set;}
public Address Address2 {get; set;}
public Phone Phone1 {get;set;}
}
例如,其中每个 Property 也是一个具有自己的 EditorTemplates 的模型类
public class Name
{
[Required]
public string FirstName {get; set;}
public string MiddleName {get; set;}
[Required]
public string LastName {get; set;}
}
并有 Name.cshtml EditorTemplate 如下
<div >
@Html.TextBoxFor(m=>m.FirstName);
@Html.TextBoxFor(m=>m.MiddleName);
@Html.TextBoxFor(m=>m.LastName);
<div>
Address.cshtml 和 Phone.cshtml 类似
在 web.config 中:-
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
单击空表单上的注册按钮时,它会通过 ajax 发布到注册 [HttpPost] 控制器方法。为什么它不给我客户端验证消息,我认为它称为不显眼的验证?我也没有在控制台中看到任何错误。