I think I’m missing something simple, but I’m blinded by looking at the same code over and over and could use another set of eyes.
I have an MVC partial view that contains a 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>
This view also contains some 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>
Here is the controller method that gets executed
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
if (CheckSuccess())
{
return Json(new { success = true });
}
return ViewNoLayout("otherView", viewModel);
}
This View gets loaded into a jQuery.UI dialog. The first time the dialog is loaded, clicking the submit button on the form executes the success function correctly – The alert pops, the dialog is closed and the parent function is called. If I popup the dialog again and click the submit button, the call goes to the server and processes correctly, but the page reloads and only displays the JSON string (no alert, etc…). I’m assuming that there is some sort of client-side caching that I’m missing, or something equivalent. Any ideas?
Remove the
document.readyfrom your view:The reason for that is that the
document.readyis no longer executed the second time when you inject the partial into your DOM. So your submit event doesn’t get attached anymore. Be careful gotcha ahead: removing thedocument.readymeans that you must place this script after the form in the markupor the first time you load this page it won’t attach it at all.Obviously all this that I am saying is only to solve your current issue.
But your real problem is the fact that you are mixing markup and HTML. This should never be done. Markup belongs to views, script belongs to javascript files. Separate javascript files. So you should externalize this into a separate js file. So the real solution is to have the following script in a separate file using the
.on()(or.delegate()if you are using legacy jQuery versions and.live()if you are using a prehistoric version of jQuery) to lively subscribe to elements that might not yet be present on your DOM at the moment of subscription: