我擁有包含所有腳本的佈局頁面,如下所示。MVC4中不引人注意的客戶端驗證不起作用
<!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>
我的帳戶Model類是如下:
public class Account
{
public Name name {get; set;}
public Address Address1 {get; set;}
public Address Address2 {get; set;}
public Phone Phone1 {get;set;}
}
其中每個屬性也有自己的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]控制器方法。爲什麼它不給我客戶端驗證消息,我認爲它被稱爲Unobtrusive驗證?我在控制檯中也看不到任何錯誤。
它工作。只是想知道爲什麼我們需要顯式調用form.valid()。它不應該沒有明確的調用工作嗎?至少這是我一直在閱讀所有基本的不顯眼驗證的例子。 – user2232861
@user檢查你正在關注的示例,表單可能已經提交了按鈕。該插件執行驗證以響應表單的提交事件 –
我曾使用submit button.it不起作用,但它仍然會執行ajax回發。這是與ajax文章有關嗎? – user2232861