Samirovic Samirovic - 3 months ago 31x
Ajax Question mvc index action is called automatically after ajax

I have an action that creates a record in the database:

public ActionResult Create([Bind(Include = "Id,Name,Description")] SampleViewModel sampleVM)
this.ShowMessage(new ToastMessage(ToastType.Success, "Record Added", ToastrDisplayType.TopLeft));
catch (Exception ex)
this.ShowMessage(new ToastMessage(ToastType.Error, ex.Message, ToastrDisplayType.TopLeft));
return Json("failed");

return Json("success");

this Action is called by AJAX:

$().ready(function () {
$("#btnSave").click(function () {
var serviceURL = '';

var sample = {
"Id": $('#hdnId').val(),
"Name": $("#txtName").val(),
"Description": $("#txtDescription").val(),

if (save_method == 'add') {
serviceURL = '@Url.Action("Create", "Samples")';
else if (save_method == 'edit') {
serviceURL = '@Url.Action("Edit", "Samples")';

type: "POST",
url: serviceURL,
data: addRequestVerificationToken(sample),
success: function (data, textStatus, jqXHR) {


The problem is that the Index Action is called automatically after the Create Action:

public ActionResult Index()
return View();

Fiddler snapshot

The Toast message is not displayed because the Index Action is called, How can I call the Create Action only (without calling the Index Action)?


So your "#btnSave" is a <button type="submit" /> button. The browser will do the following in order:

  1. Invoke your own click handler, that you have shown in your code.
  2. Post the <form> that your button is in to the server and reload the page with the answer that it gives.

You have two options: either you remove the form and have a regular <button> (without type="submit"), or you modify your click handler a little:

$("#btnSave").click(function (event) {
        event.preventDefault(); // notice this line
        var serviceURL = '';