我的工作代码
JavaScript/JQuery
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function StartValidation() {
var result = AjaxCall();
return result;
}
function AjaxCall() {
var Istrue = false;
$.ajax({
url : "@Url.Action("Json", "FileUpload")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({FirstName:'test', LastName:'test1'})
}).done(function() {
Istrue = true;
alert('ok')
})
.fail(function() {
Istrue = false;
alert('not ok');
});
return Istrue;
}
</script>
HTML
@using (Ajax.BeginForm("UploadRequestFile", "FileUpload", new AjaxOptions
{
HttpMethod = "POST",
OnBegin = "return StartValidation();"
}, new { id = "frmUp" }))
{
<input type="submit" name="Submit" value="Submit" />
}
运行时标记
<form method="post" id="frmUp" data-ajax-method="POST"
data-ajax-begin="return StartValidation();" data-ajax="true"
action="/fileupload/UploadRequestFile?Length=10">
<input type="submit" value="Submit" name="Submit">
</form>
检查 data-ajax-method、data-ajax-begin 和 data-ajax 属性。Ajax.BeginForm 助手发出这些属性。这些属性对浏览器毫无意义。理解和解释它们的是 jquery.unobtrsuive-ajax.js 脚本。没有它。因此,无需显式执行提交。
动作方法
[HttpPost]
public JsonResult Json(string FirstName, String LastName)
{
//Do the Validation Part here.
return Json(new { Success = true });
}
[HttpPost]
public ActionResult UploadRequestFile()
{
return View();
}