我想我错过了一些简单的东西,但我被一遍又一遍地看同一个代码弄瞎了眼睛,可能需要另一双眼睛。
我有一个MVC部分视图,其中包含一个Form.
<div class="Clear"></div>
<div class="OverFlow">
@using (Html.BeginForm(null, null, FormMethod.Post, new {id = "formId"}))
{
<div class="ErrorBx1">@Html.GetData()</div>
<table>
@Html.EditorFor(m => m.FormModel, "MyEditorTemplate")
<tr>
<td colspan="2"></td>
<td><input type="image" src="@Images.ResolveDefault("btn-send.jpg")" alt="Send" class="Send" /></td>
</tr>
</table>
}
</div>
此视图还包含一些Javascript
<script type="text/javascript">
$(function () {
$('#formId').submit(function () {
$.ajax({
cache: false,
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (res) {
if (res.success) {
alert("success");
closeDialog();
window.parent.specialFunction();
} else {
alert("not success");
$('#someElement').replaceWith(res);
}
}
});
return false;
});
});
</script>
以下是执行的控制器方法
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
if (CheckSuccess())
{
return Json(new { success = true });
}
return ViewNoLayout("otherView", viewModel);
}
该视图加载到jQuery.UI对话框中。第一次加载对话框时,单击表单上的提交按钮将正确执行成功功能-弹出警报,关闭对话框并调用父函数。如果我再次弹出对话框并单击提交按钮,调用将转到服务器并正确处理,但页面会重新加载并只显示JSON字符串(没有警报等)。我假设我缺少某种客户端缓存,或者类似的东西。有什么想法吗?
从视图中删除document.ready
:
<script type="text/javascript">
$('#formId').submit(function () {
$.ajax({
cache: false,
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (res) {
if (res.success) {
alert("success");
closeDialog();
window.parent.specialFunction();
} else {
alert("not success");
$('#someElement').html(res);
}
}
});
return false;
});
</script>
原因是当您将partial注入DOM时,document.ready
第二次不再执行。因此,您的提交事件不再附加。请注意:删除document.ready
意味着您必须将此脚本放在标记中的表单之后,否则第一次加载此页面时它根本不会附加它。
显然,我所说的一切只是为了解决你当前的问题。
但真正的问题是,您将标记和HTML混合在一起。永远不应该这样做。标记属于视图,脚本属于javascript文件分离javascript文件。因此,您应该将其外部化为一个单独的js文件。因此,真正的解决方案是在一个单独的文件中使用.on()
(或者.delegate()
,如果您使用的是遗留的jQuery版本,.live()
,如果您正在使用jQuery的史前版本)来live订阅在订阅时可能还没有出现在DOM上的元素:
$(document).on('submit', '#formId', function() {
$.ajax({
cache: false,
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (res) {
if (res.success) {
alert("success");
closeDialog();
window.parent.specialFunction();
} else {
alert("not success");
$('#someElement').html(res);
}
}
});
return false;
});