美好的一天,
我正在尝试在我的asp.Net MVC项目中使用ajax.beginform,以创建成功警报。 问题是我无法使其工作,我也没有收到任何错误消息。
[HttpPost]
public ActionResult Create(Details details)
{
//do something
//add details to db
return View("Create", details);
}
public class Details
{
public string Name { get; set; }
public string Email { get; set; }
}
这是我的观点
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
@using (Ajax.BeginForm("Create", new AjaxOptions()
{
OnSuccess= "ajaxSuccess"
}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true, "Please fix the following errors.")
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
}
@section scripts
{@Scripts.Render("~/bundles/jqueryval")
<script>
function ajaxSuccess () { alert('this is ajaxSuccess'); }
$(document).ready(function ()
{
function ajaxSuccess () { alert('this is ajaxSuccess'); }
});
</script>
}
如您所见,我使用的是Jquery.unobstrusive-ajax.min.js
脚本。我的操作已完成并返回到视图,但我的控制台中没有错误,也没有警报。我错过了什么吗?
更新:我已为文档添加了警告,但没有触发 **更新2:**更改了函数ajaxSuccess(){alert('this is ajaxSuccess'); }
答案 0 :(得分:0)
首先,查看“网络”标签,查看脚本是否正确解析,或者是否返回了404。
同时尝试不使用tilda和本地路径查看它是否有效:
<script src="../Scripts/jquery-1.8.2.min.js"></script>
<script src="../Scripts/jquery.unobtrusive-ajax.min.js"></script>
或者使用这种方法的tilda:Using tilde in script tag src attribute
编辑:由于内部功能,您未在document.ready
收到警报;改变:
$(document).ready(function ()
{
function ajaxSuccess () { alert('this is ajaxSuccess'); }
});
为:
$(document).ready(function () {
alert('this is document ready');
});
你可能会看到警报。