I'd like to have a button do a simple POST in order to kick-off some work in the controller on the backend:
<button type="button" asp-action="DoIt">Do it<button>
[HttpPost]
public async Task<IActionResult> DoIt()
{
}
Can I do this in ASP.NET Core without using a form?
I know I can do something like this:
<button onClick="$.post('/MyController/DoIt');" type="button">DoIt</button>
But it would be cool if something similar to following would be possible:
<button asp-controller="DoIt" asp-method="POST" type="button">DoIt</button>
Ideally, ValidateAntiForgeryToken would be supported too...
You want to make an ajax call from javascript.
Fetch API example.
fetch("URL", {
method: "POST", // HTTP Method
body: JSON.stringify({}) // Data to send
});
$.ajax({
url: "", // URL to post to
method: "POST", // HTTP Method
data: JSON.stringify({}) // Data to send
});
HTML
------
@Html.Hidden("cancelOrder", Url.Action("MethodName", "ControllerName"))
AJAX Call
----------
$.ajax({
url: $("#cancelOrder").val(),
type: "POST",
data: { ID: Id},
success: function (_result) {
//Success
}
});
Method
------
public JsonResult MethodName()
{
bool _status = true;
try
{
return Json(_status, JsonRequestBehavior.AllowGet);
}
catch
{
throw;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.