在ajax之后自动调用asp.net mvc index action

时间:2016-07-12 08:17:36

标签: ajax asp.net-mvc

我有一个在数据库中创建记录的操作:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Name,Description")] SampleViewModel sampleVM)
    {
        try
        {
            _service.Add(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");
    }

这个动作由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")';
            }

            $.ajax({
                type: "POST",
                url: serviceURL,
                data: addRequestVerificationToken(sample),
                success: function (data, textStatus, jqXHR) {
                    handleAjaxMessages();
                },

            });
        });
    });

问题是在创建操作后自动调用索引操作:

[HttpGet]
    public ActionResult Index()
    {
        return View();
    }

Fiddler snapshot

由于调用了索引操作,因此不显示Toast消息,如何仅调用Create Action(不调用Index Action)?

1 个答案:

答案 0 :(得分:0)

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 = '';