I've found examples of have multiple handlers on a page and the associated naming convention (ie OnPostXXX) and 'asp-post-hanlder' tag helper. But how can I call one of these methods from an AJAX call.
I have an older example with a typical MVC view and controller but how does this work with a Razor Page?
For example if I take the base application and modify the About.cshtml page to the following:
@page
@model AboutModel
@{
ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@Model.Message</h3>
<input type="button" value="Ajax test" class="btn btn-default" onclick="ajaxTest();" />
@section Scripts {
<script type="text/javascript">
function ajaxTest() {
console.log("Entered method");
$.ajax({
type: "POST",
url: '/About', // <-- Where should this point?
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status, errorThrown) {
var err = "Status: " + status + " " + errorThrown;
console.log(err);
}
}).done(function (data) {
console.log(data.result);
})
}
</script>
}
And on the model page About.cshtml.cs
public class AboutModel : PageModel
{
public string Message { get; set; }
public void OnGet()
{
Message = "Your application description page.";
}
public IActionResult OnPost() {
//throw new Exception("stop");
return new JsonResult("");
}
}
The OnPost is not called from the Ajax call.
The AntiForgery Token needs to be added and there needs to be a form element on the page.
in your Startup.Cs Add this before services.AddMvc()
thenn in your ajax, change to:
then in your method add
On the cshtml page wrap the button in a form or no AntiForgery cookie will be added.
After looking at the answers above I got JSON ajax to work with .NET Core 2.1 Razor pages using Visual Studio 2017 Preview 2:
Startup.cs
PostJson.cshtml
PostJson.cshtml.cs
Browser
http://localhost:44322/postJson
Please see this related section of the documentation https://docs.microsoft.com/en-us/aspnet/core/mvc/razor-pages/?tabs=visual-studio
/Pages/Index.cshtml maps to / or /Index
/Pages/Contact.cshtml maps to /Contact
Everything works well, but some changes have to be made:
1)Open Startup.cs:
2)Open HomeController.cs:
3)Open About.cshtml:
It should be noted that "onPost" was added inside the controller, so in AJAX the correct "url" should be indicated. Then:
The answer works for me. I would only add that if we have customized methods on the page like:
Then we should specify the handler name in the url: