A set of technologies in .NET for building web applications and web services. Miscellaneous topics that do not fit into specific categories.
Please try the followings:
(1) Add form tag to .cshtml.
(2) Create the FormData object form the form tag.
(3) Send the FormData using jQuery ajax or fetch API.
Shown below are the samples:
Model
namespace RazorPages.Models
{
public class PersonModel
{
public string Name { get; set; } = string.Empty;
public string DateTime { get; set; } = string.Empty;
}
}
.cshtml.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPages.Models;
namespace RazorPages.Pages
{
public class AjaxPostModel : PageModel
{
public void OnGet()
{
}
[BindProperty]
public PersonModel Model { get; set; } = default!;
public IActionResult OnPost()
{
if (Request.Headers.XRequestedWith == "XMLHttpRequest")
{
string name = Model.Name;
string dateTime = Model.DateTime;
return Content($"Name: {name}, DateTime: {dateTime}");
}
else
{
return BadRequest();
}
}
}
}
.cshtml
@page
@model RazorPages.Pages.AjaxPostModel
@{
ViewData["Title"] = "AjaxPost";
}
<h1>AjaxPost</h1>
<hr />
<form method="post">
<input type="text" name="name" />
<br />
<input type="text" name="datetime" />
<br />
</form>
<input type="button" id="ajaxPost" value="POST" />
<div id="result"></div>
@section Scripts {
<script type="text/javascript">
//<![CDATA[
document.getElementById("ajaxPost")
.addEventListener('click', async () => {
const fd = new FormData(document.querySelector("form"));
const result = document.getElementById("result");
const param = {
method: "POST",
body: fd,
// set X-Requested-With in request header
headers: { 'X-Requested-With': 'XMLHttpRequest' }
}
const response = await fetch("/ajaxpost", param);
if (response.ok) {
const data = await response.text();
result.innerText = data;
} else {
result.innerText = "response.ok is false";
}
});
//]]>
</script>
}
CSRF token in cookie sent to the server:
CSRF token in hidden field sent to the server:
Result
To see if the validation of CSRF-token is working, delete cookie of browser after the browser has received the response of OnGet() method and send the FormData by clicking the [POST] button. The ASP.NET will return 400 Bad request without invoking the OnPost() method.