我在局部视图中有一个表单,表单没有触发AjaxOptions中指定的客户端javascript方法,我看不出原因。
我有以下表格。
@model QuickContact
<div id="quickContactForm" class="row">
<div class="col-md-4 push-md-9 box">
<h4>Quick Contact</h4>
<div id="contactForm"></div>
<p>
For an instant callback simply fill in the form below.
</p>
@using (Ajax.BeginForm(
"QuickContact",
"Contact",
new AjaxOptions
{
OnFailure = "contact.onFailure",
OnBegin = "contatc.onBegin",
OnComplete = "contact.onComplete",
OnSuccess = "contact.onSuccess",
UpdateTargetId = "quickContactForm"
}))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.EditorFor(x => x.Name, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter your name..." } })
@Html.ValidationMessageFor(x => x.Name, null, new { @class = "text-danger" })
@Html.EditorFor(x => x.Telephone, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter your telephone..." } })
@Html.ValidationMessageFor(x => x.Telephone, null, new { @class = "text-danger" })
<input type="submit" class="btn btn-block btn-primary" value="Submit" />
</div>
}
<div id="loading" class="row">
<div class="col-md-12">
<p class="text-lg-center">
<i class="fa fa-spinner" aria-hidden="true"></i>
</p>
</div>
</div>
</div>
</div>
我的js是;
var contact = {
onBegin: function() {
console.log("loading...");
$('#loading').show();
},
onComplete: function() {
console.log("complete");
$("#loading").hide();
},
onFailure: function(ajaxContext) {
console.log("error occured.");
var response = ajaxContext.responseText;
alert("Error Code [" + ajaxContext.ErrorCode + "] " + response);
$('#loading').hide();
},
onSuccess: function(result) {
// enable unobtrusive validation for the contents
// that was injected into the <div id="result"></div> node
console.log("ajax success func");
$.validator.unobtrusive.parse($(result));
}
};
我还使用
为unobtrusive-ajax安装了nuget包Install-Package Microsoft.jQuery.Unobtrusive.Ajax
在我的web.config中我有
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
最后,我已经将unobtrusive-ajax链接添加到我的捆绑中;
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive-ajax.js",
"~/Scripts/jquery.validate*",
"~/Scripts/tether/tether.js"));
我没有得到任何控制台错误,但POST正在执行控制器操作,并且我的ajax控制台日志都没有注册。
我在这里做错了什么想法?
答案 0 :(得分:0)
您的代码看起来很好。只需确保您的OnBegin
属性值正确无误。它应该是contact.onBegin
而不是contatc.onBegin
onBegin
函数定义在contact
上,而不是contatc
这应该有用。
@using (Ajax.BeginForm(
"QuickContact",
"Contact",
new AjaxOptions
{
OnFailure = "contact.onFailure",
OnBegin = "contact.onBegin",
OnComplete = "contact.onComplete",
OnSuccess = "contact.onSuccess",
UpdateTargetId = "quickContactForm"
}))
{
<!-- Your form controls goes here -->
}
我尝试了这段代码,并将消息记录到我的控制台。
您可能还想包含jquery.validate.unobtrusive.js
库。