更新 2:
jQuery 版本兼容性问题。
更新1:
我的脚本参考中有一个错字。但是我现在遇到这个问题:
TypeError: $(...).live is not a function
$("a[data-ajax=true]").live("click", function (evt) {
======================================
当我在控制器中通过 ajax.beginform 提交有效表单时,它返回显示在视图中的 JSON,而不是由回调函数处理,我不知道为什么会这样。
我从网上拿了一个演示项目,以防万一它看起来很熟悉。
HTML/JS
@model Unobtrusive_Validation.Models.BlogPost
<html>
<head>
</head>
<body>
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.unobtrusive.ajax.js"></script>
@using (Ajax.BeginForm("Test", "BlogPost",
new AjaxOptions{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnBegin = "alert('OnBegin')",
OnComplete = "alert('OnComplete')",
OnFailure = "alert('OnFailure')"
} )
)
{
@Html.ValidationSummary(true)
<fieldset>
<legend>BlogPost</legend>
<div class="editor-label">
@Html.LabelFor(model => model.PostedOn)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.PostedOn)
@Html.ValidationMessageFor(model => model.PostedOn)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Content)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Content)
@Html.ValidationMessageFor(model => model.Content)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Category)
@Html.ValidationMessageFor(model => model.Category)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
</body>
<script type='text/javascript'>
function OnSuccess(result) {
console.log(result);
if (result.success == false) {
alert("failed");
}
}
</script>
</html>
控制器:
public class BlogPostController : Controller
{
// GET: /BlogPost/Create
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Test(BlogPost _model)
{
return Json(new {success = false} );
}
}
网页配置
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />