[英]Asp.Net-Core with Razor Pages web app send values on Post method
Is it possible in Asp.Net-Core Webb Application with Razor Pages to send some values via the url and post method?是否可以在带有 Razor 页面的 Asp.Net-Core Webb 应用程序中通过 url 和 post 方法发送一些值? I know that in MVC you would use the HttpPost method, but that is not possible in.Net Core.我知道在 MVC 中你会使用 HttpPost 方法,但这在.Net Core 中是不可能的。
For example, in my js file I have this function that receives a parameter a:例如,在我的 js 文件中,我有这个接收参数 a 的 function:
function redirect(a)
{
$.ajax({
type: 'POST',
url: './MyPage', //I also tried @Url.Page("SetValue")'
dataType: 'int',
data: { a },
});
}
I want to be able to send that value to my Razor Page, something like this:我希望能够将该值发送到我的 Razor 页面,如下所示:
public void OnPostSetValue(int a)
{
Debug.WriteLine(a); //here I will use the value
}
But I am getting this error: "Failed to load resource: the server responded with a status of 500 () [https://localhost:44350/MyPage]"但我收到此错误:“加载资源失败:服务器响应状态为 500 () [https://localhost:44350/MyPage]”
I know that probably this is not the way to do it, but I only found examples for MVC.我知道这可能不是这样做的方法,但我只找到了 MVC 的示例。 Is there any way I can do this here in Asp.Net Core?有什么办法可以在 Asp.Net Core 中做到这一点?
But I am getting this error: "Failed to load resource: the server responded with a status of 500 () [https://localhost:44350/MyPage]"但我收到此错误:“加载资源失败:服务器响应状态为 500 () [https://localhost:44350/MyPage]”
You can do it in the Asp.Net Core with Razor Pages.您可以在 Asp.Net Core 中使用 Razor 页面进行操作。
First of all, there is no specific post method name
specified in your url
in ajax.首先,在url
中的 url 中没有指定特定post method name
。
Secondly, there is a special requirement when using ajax to pass parameters in the Razor Pages, we must provide the anti-forgery token ourselves , which means we need to add @Html.AntiForgeryToken()
in your page view, then add headers
in ajax to pass the anti-forgery token. Secondly, there is a special requirement when using ajax to pass parameters in the Razor Pages, we must provide the anti-forgery token ourselves , which means we need to add @Html.AntiForgeryToken()
in your page view, then add headers
in ajax传递防伪令牌。
For more details, please refer to this .更多详情,请参阅此。
Here is the complete example:这是完整的示例:
@page
@model WebApplication_razorpage_new.Pages.MyPageModel
@{
ViewData["Title"] = "MyPage";
Layout = "~/Pages/Shared/_Layout.cshtml";
}
@Html.AntiForgeryToken()
<input id="Button1" type="button" value="button" onclick="redirect(1)" />
@section Scripts{
<script>
function redirect(a) {
$.ajax({
type: 'POST',
url: '@Url.Page("MyPage", "SetValue")',
dataType: 'int',
data: {a},
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
}
});
}
</script>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.