Vince Vince - 8 days ago 5
Javascript Question

ASP.Net MVC & JQuery Ajax - page is replaced with json result

I'm doing an ajax call to update an entity then in the mvc controller i return the state success = true || false with errors.

My problem came from the return of the controller.
The page is changeing, url become the url of the mvc controller action and the content of the page is the json result.

What is the cause of this problem ?

Here is the code of my javascript method:

$("#submit-button").on("submit", "#formId", function (e) {
e.preventDefault();

var form = $(this);

$.ajax({
url: form.attr("action"),
dataType: 'Json',
method: form.attr("method"),
data: form.serialize(),
success: function (data) {
console.log(data);
}
});
});


Here is the code of my Controller:

[HttpPost]
public JsonResult UpdateEntity(UpdateEntityViewModel model)
{
if (ModelState.IsValid)
{
_updateEntityService.Execute(model);
return Json(new { success = true });
}

return Json(new { success = false, ModelState.GetErrors() });
}


if anyone can point me out what i'm doing wrong!
thanks in advance.

EDIT:

Here is the form code:

@using (Html.BeginForm("Entity", "UpdateEntity", new { Area = "MyArea" }, FormMethod.Post, new { @id = "formId" }))
{
// ... form code

<button id="submit-button" type="submit" class="btn btn-primary">
Modifier
</button>
}

Answer

Change your script to

$("#formId").submit(function(e) {
    e.preventDefault();
    var form = $(this);
    $.ajax({
        ....
    });
});

You current script is handling the submit event of a <form id="formId" ... > element that exists inside your <button id="submit-button" ..> element which does not exist (the button is inside the form) and as a result the script is never executed and your making a normal submit which returns the JsonResult to a new page.

Comments