I've a onpost method in .net core pagemodel class like below
public void OnPostLoad(string TZ)
{
///..statements..////
}
and i need to call the above method from my razor page - jquery ready function i've tried like below but it's not worked for me
$(document).ready(function(){
$.post(base_url "/Transactions/Index?handler=Load=" {TZ:timezone }, response => {
alert("test timezone");
});
});
please let me know if you have any solutions for it. thanks
CodePudding user response:
Request Verification is baked into the Razor Pages framework. If you use ajax to post data, it needs anti-forgery token verification.
1.If your page contains form. The form tag helper injects a hidden form field named __RequestVerificationToken
at the end of every form with an encrypted value representing the token. You just need add headers for this token:
<form method="post">
//...
</form>
@section Scripts
{
<script>
$(document).ready(function(){
var timezone = "aaa";
$.ajaxSetup({
headers: {
RequestVerificationToken:$('input:hidden[name="__RequestVerificationToken"]').val()
}
});
$.post(base_url "/Transactions/Index?handler=Load&TZ=" timezone ,response => {
alert("test timezone");
});
});
</script>
}
2.If your page does not contain any form, you can turn off anti-forgery token verification and then you no need add RequestVerificationToken
header any more:
In ASP.NET 6
builder.Services.AddRazorPages().AddRazorPagesOptions(o =>
{
o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
});
In ASP.NET Core 3.x or .NET 5
services.AddRazorPages().AddRazorPagesOptions(o =>
{
o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
});
3.If your page does not contain form and you also do not want to turn off anti-forgery token verification, you can automatically add @Html.AntiForgeryToken()
:
@Html.AntiForgeryToken()
@section Scripts
{
<script>
$(document).ready(function(){
var timezone = "aaa";
$.ajaxSetup({
headers: {
RequestVerificationToken:$('input:hidden[name="__RequestVerificationToken"]').val()
}
});
$.post(base_url "/Transactions/Index?handler=Load&TZ=" timezone ,response => {
alert("test timezone");
});
});
</script>
}