Jquery 为什么这个AJAX表单在MVC5中不起作用?
我正在为该网站建立一个联系表单,该表单用于ASP.NETMVC5应用程序(RazorEngine)和.NET4.5。表单显示正确,并且似乎验证正确,但是AJAX部分根本不起作用 其思想是,当用户按下SUBMIT并且所有验证都成功时,服务器将通过AJAX发送电子邮件。在这段时间内,页面应该显示“正在进行”的旋转图标,我们可以看到所有AJAX内容。完成后,服务器返回一个JSON响应,指示是否成功,并返回一条消息。当流程完成时,此信息将显示在divResult上 但正如我所说,当我按下submit时,会显示进度动画,发送电子邮件,而不是在我的DIV中获取JSON结果,整个页面被原始JSON响应替换。我错过了什么 我的EmailModel如下(为了简洁起见,省略了验证属性): “接收者”只是一种构造,我在联系人表单中显示标签列表,而不是电子邮件地址,例如“信息”、“反馈”等。它在视图中显示为带有给定“标签”的下拉列表,其中一个是预选的 我的ItemViewModel如下所示:Jquery 为什么这个AJAX表单在MVC5中不起作用?,jquery,ajax,asp.net-mvc,asp.net-mvc-5,Jquery,Ajax,Asp.net Mvc,Asp.net Mvc 5,我正在为该网站建立一个联系表单,该表单用于ASP.NETMVC5应用程序(RazorEngine)和.NET4.5。表单显示正确,并且似乎验证正确,但是AJAX部分根本不起作用 其思想是,当用户按下SUBMIT并且所有验证都成功时,服务器将通过AJAX发送电子邮件。在这段时间内,页面应该显示“正在进行”的旋转图标,我们可以看到所有AJAX内容。完成后,服务器返回一个JSON响应,指示是否成功,并返回一条消息。当流程完成时,此信息将显示在divResult上 但正如我所说,当我按下submit时,
public class ItemViewModel {
public string SelectedId { get; set; }
public IEnumerable<SelectListItem> Items { get; set; }
}
EmailModel model = new EmailModel() { ... properties set here ... }
return view(model);
该视图将调用以下同样可以正常工作的控制器方法(Post):
[HttpPost]
public JsonResult SendContactMail(Models.EmailModel model) {
ResponseModel response;
try {
if (ModelState.IsValid) {
response = SendEmail(model); // pretty obvious what it does and it works
} else {
response = new ResponseModel { Success = false, ResponseText = "hum..." };
}
} catch (Exception ex) {
response = new ResponseModel { Success = false, ResponseText = ex.Message };
}
}
最后,我的Razor视图大致如下所示:
@model Models.EmailModel;
@using System.Web.Mvc.Ajax;
@{
ViewBag.Title = "contact form";
System.Web.Mvc.Ajax.AjaxOptions ajaxopts = new AjaxOptions() {
HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "divResult",
OnBegin = "OnBegin", OnComplete = "OnComplete", OnSuccess = "OnSuccess", OnFailure = "OnFailure"
};
@using (Ajax.BeginForm("SendContactMail", "Mail", null, ajaxopts,
new { @encType = "multipart/form-data", @id = "contactusform",
@name = "contactusform" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Subject)
@Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FromEmail)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FromEmail)
@Html.ValidationMessageFor(model => model.FromEmail)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.FromName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FromName)
@Html.ValidationMessageFor(model => model.FromName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Receptor)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Receptor.SelectedId, Model.Receptor.Items, new { @class = "select1" })
@Html.ValidationMessageFor(model => model.Receptor)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.MessageBody)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.MessageBody)
@Html.ValidationMessageFor(model => model.MessageBody)
</div>
<p>
<input type="submit" name="operation" id="process" value="Send" class="btn btn-info" />
</p>
</fieldset>
<div id="divProcessing" style="text-align: center;">
<img src="/Images/ajax-loader.gif" /><br />
<p>@Resources_Controller_Mail.Msg_SendingEmail</p>
</div>
<div id="divMsg"></div>
<div id="divResult"></div>
} @* ajax.beginform *@
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
// Hide the "busy" Gif at load:
$("#divProcessing").hide();
$("#divMsg").hide();
// Attach click handler to the submit button:
$('#process').click(function () {
$('#contactusform').submit();
});
// Handle the form submit event, and make the Ajax request:
$("#contactusform").on("submit", function (event) {
event.preventDefault();
// Show the "busy" Gif:
$("#divProcessing").show();
$("#divResult").empty();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
url: url,
type: "POST",
data: formData,
dataType: "json",
success: function (resp) {
// Hide the "busy" gif:
$("#divProcessing").hide();
// Do something useful with the data:
// var image = resp.Success ? "/Images/Yes.png" : "/Images/No.png";
//$("<h3><img src=\"" + image + "\"/></h3>" + "<p>" + resp.ResponseText + "</p>").appendTo("#divResult");
$("<h3>" + resp.Success + "</h3>" + "<p>" + resp.ResponseText + "</p>").appendTo("#divResult");
}
})
});
});
function OnBegin() {
$("#divMsg").append("Ajax Begins");
$("#divMsg").show();
}
function OnComplete() {
$("#divMsg").append("Ajax Complete");
$("#divMsg").show();
}
function OnSuccess() {
$("#divMsg").append("Success");
$("#divMsg").show();
}
function OnFailure() {
$("#divMsg").append("Failed");
$("#divMsg").show();
}
</script>
}
@model Models.EmailModel;
@使用System.Web.Mvc.Ajax;
@{
ViewBag.Title=“联系方式”;
System.Web.Mvc.Ajax.AjaxOptions ajaxopts=new AjaxOptions(){
HttpMethod=“Post”,InsertionMode=InsertionMode.Replace,UpdateTargetId=“divResult”,
OnBegin=“OnBegin”,OnComplete=“OnComplete”,OnSuccess=“OnSuccess”,OnFailure=“OnFailure”
};
@使用(Ajax.BeginForm(“SendContactMail”、“Mail”、null、ajaxopts、,
新的{@encType=“multipart/form data”,@id=“contactusform”,
@name=“contactusform”})
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@LabelFor(model=>model.Subject)
@EditorFor(model=>model.Subject)
@Html.ValidationMessageFor(model=>model.Subject)
@LabelFor(model=>model.FromEmail)
@Html.EditorFor(model=>model.FromEmail)
@Html.ValidationMessageFor(model=>model.FromEmail)
@LabelFor(model=>model.FromName)
@EditorFor(model=>model.FromName)
@Html.ValidationMessageFor(model=>model.FromName)
@LabelFor(model=>model.Receptor)
@Html.DropDownListFor(model=>model.Receptor.SelectedId,model.Receptor.Items,新的{@class=“select1”})
@Html.ValidationMessageFor(model=>model.Receptor)
@LabelFor(model=>model.MessageBody)
@EditorFor(model=>model.MessageBody)
@Html.ValidationMessageFor(model=>model.MessageBody)
@资源\u控制器\u Mail.Msg\u发送电子邮件
}@*ajax.begin*@
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
$(文档).ready(函数(){
//在加载时隐藏“忙”Gif:
$(“#divProcessing”).hide();
$(“#divMsg”).hide();
//将单击处理程序附加到“提交”按钮:
$(“#进程”)。单击(函数(){
$(#contactusform')。提交();
});
//处理表单提交事件,并发出Ajax请求:
$(“#contactusform”)。在(“提交”,功能(事件){
event.preventDefault();
//显示“忙碌”Gif:
$(“#divProcessing”).show();
$(“#divResult”).empty();
var url=$(this.attr(“操作”);
var formData=$(this.serialize();
$.ajax({
url:url,
类型:“POST”,
数据:formData,
数据类型:“json”,
成功:功能(resp){
//隐藏“忙碌”gif:
$(“#divProcessing”).hide();
//对数据执行一些有用的操作:
//var image=resp.Success?/Images/Yes.png:“/Images/No.png”;
//$(“+”“+resp.ResponseText+””)。附录(“#divResult”);
$(“+resp.Success++”“+resp.ResponseText+””).appendTo(“#divResult”);
}
})
});
});
函数OnBegin(){
$(“#divMsg”).append(“Ajax开始”);
$(“#divMsg”).show();
}
函数OnComplete(){
$(“#divMsg”).append(“Ajax完成”);
$(“#divMsg”).show();
}
函数OnSuccess(){
$(“#divMsg”)。追加(“成功”);
$(“#divMsg”).show();
}
函数OnFailure(){
$(“#divMsg”).append(“失败”);
$(“#divMsg”).show();
}
}
现在,在有人询问之前,布局会在HTML表单标记关闭后以及上面显示的具有.ready()函数的脚本之前在视图中插入/呈现以下内容:
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="/Scripts/bootstrap.js"></script>
<script src="/Scripts/respond.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
正如建议的那样,这些文件被插入到HEAD部分(感谢您的提示!)。它们来自MicrosoftMvcAjax.Mvc5 NuGet包,该包将它们放在~/Scripts文件夹中:
<script type="text/javascript" src="/Scripts/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/Scripts/MicrosoftMvcAjax.js"></script>
因此,总结
- 为什么视图上没有AJAX进度活动
- 为什么视图在提交时的行为类似于常规HTTP post(没有ajax)
- 您没有包括ajax
<script src="/Content/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="/Content/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
改为在HTML中:
<input type="submit" name="operation" id="process" value="Send" class="btn btn-info" /> ...
进入
谢谢@Tony的提示,我确实错过了这些。添加了MicrosoftMvcAjax.Mvc5 NuGet包
<input type="submit" name="operation" id="process" value="Send" class="btn btn-info" /> ...
<button id="process" value="Send" class="btn btn-info" >Submit</button> ...
// Handle the form submit event, and make the Ajax request:
$("#contactusform").on("submit", function (event) {
event.preventDefault();
// Show the "busy" Gif:
$("#divProcessing").show();
$("#divResult").empty();
var url = $(this).attr("action");
var formData = $(this).serialize();
// Handle the form submit event, and make the Ajax request:
$("#process").on("click", function (event) {
event.preventDefault();
// Show the "busy" Gif:
$("#divProcessing").show();
$("#divResult").empty();
var url = $('#contactusform').attr("action");
var formData = $('#contactusform').serialize();