我有一个在数据库中创建记录的操作:
[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();
}
由于调用了索引操作,因此不显示Toast消息,如何仅调用Create Action(不调用Index Action)?
答案 0 :(得分:0)
So your "#btnSave"
is a <button type="submit" />
button. The browser will do the following in order:
<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 = '';