On my MVC View I have button:
<input id="btnSave" type="submit" name="Save" value="Save" />
When I click this button I need call one Action, do some stuff there and then Submit my form.
I have this jQuery:
$('#btnSave').click(function () {
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Then I want to submit my form. In Controller I have 2 Actions:
public ActionResult SaveDetailedInfo(Option[] Options)
{
return Json(new { status = "Success", message = "Success" });
}
[HttpPost]
public ActionResult Save()
{
return RedirectToAction("Index", "Home");
}
The problem is when I have type="submit"
in my button, I can't reach SaveDetailedInfo
Action, cause ajax gives me error
, but when I remove type="submit"
, ajax works fine, but Save
Action never executes.
Please, any ideas how to execute both Actions? I thought maybe after Ajax > Success
try to add type=submit
through jquery and use .click()
, but it sounds strange to me.
This question is related to
javascript
jquery
ajax
asp.net-mvc
asp.net-mvc-4
Your C# action "Save" doesn't execute because your AJAX url is pointing to "/Home/SaveDetailedInfo" and not "/Home/Save".
To call another action from within an action you can maybe try this solution: link
Here's another better solution : link
[HttpPost]
public ActionResult SaveDetailedInfo(Option[] Options)
{
return Json(new { status = "Success", message = "Success" });
}
[HttpPost]
public ActionResult Save()
{
return RedirectToAction("SaveDetailedInfo", Options);
}
AJAX:
Initial ajax call url: "/Home/Save"
on success callback:
make new ajax url: "/Home/SaveDetailedInfo"
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Source: Stackoverflow.com