I have a mvc project. I open a form in a modal dialog. The user fills in form and hits save. The form posts to the controller however I am trying to intercept and post via json.
Looking in Dev tools network section as well as having alert() in my json it is not running and I am thinking it is not attached properly? I have read several pages and it seems my json is basically correct.
I know there is a relation between the parent page and a window...which is a div that becomes the modal window. However I don't know enough to determine if this is part of the break down.
In the parent window here is how my modal is launched.
$("#edit").click(function (e)
{
e.preventDefault();
var detailsWindow = $("#window").data("kendoWindow");
if (!detailsWindow)
{
// create a new window, if there is none on the page
detailsWindow = $("#window")
// set its content to 'loading...' until the partial is loaded
.html("Loading...")
.kendoWindow(
{
modal: true,
width: "800px",
height: "400px",
title: "@T("....")",
actions: ["Close"],
content:
{
url: "@Html.Raw(Url.Action("...", "..."))",
data: { ... }
}
}).data('kendoWindow').center();
}
detailsWindow.open();
});
The above code hits the controller and populates the model then loads the partial in centered modal as expected.
In the modal partial I have this:
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "formCreateEdit" }))
{
...HTML ELEMENTS...
<input type="submit" name="save" id="save" value="@T("...")" />
}
<script>
$(function()
{
$("#formCreateEdit").submit
(function (e)
{
alert(e);
e.preventDefault(); //As we will manually submit the form
$.ajax(
{
type: "POST",
url: "@Html.Raw(Url.Action("...", "..."))",
data: $(this).serialize(),
success: function (data)
{
//here we check if database called resulted in Success/Failure
if (data.Result === "Success")
{
alert('Finis');
}
else
{
//Show error message or whatever.
}
}
})
//});
});
</script>
Edit:
I have also tried intercepting the button click event. I may veru well have been doing it wrong so here is the code when I tried that:
$('#save').click(function(event)
{
event.preventDefault();
// take over and perform ajax post
alert('ddd');
$.ajax(
{
type: "POST",
url: "@Html.Raw(Url.Action("...", "..."))",
data: $(this).serialize(),
success: function (data)
{
//here we check if database called resulted in Success/Failure
if (data.Result === "Success")
{
alert('Finis');
}
else
{
//Show error message or whatever.
}
}
})
});
So it ended up being more complicated because the modal is loaded from a view after passing through the controller...thus it is considered dynamically generated. So the solution was to attach the event handler post document generation as seen here. I have linked to these two post so that the SO members who have shared their knowledge with me can get upvotes if it benefits you as well.
First Post
Second Post
Intercept the click of the submit button and not on the form.