【问题标题】:Asp.Net-Core with Razor Pages web app send values on Post method带有 Razor Pages Web 应用程序的 Asp.Net-Core 在 Post 方法上发送值
【发布时间】:2020-08-03 14:27:33
【问题描述】:

是否可以在带有 Razor 页面的 Asp.Net-Core Webb 应用程序中通过 url 和 post 方法发送一些值?我知道在 MVC 中你会使用 HttpPost 方法,但这在 .Net Core 中是不可能的。

例如,在我的 js 文件中,我有一个接收参数 a 的函数:

function redirect(a)
{
    $.ajax({
      type: 'POST',
      url: './MyPage', //I also tried @Url.Page("SetValue")'
      dataType: 'int',
      data: { a },
   });
}

我希望能够将该值发送到我的 Razor 页面,如下所示:

public void OnPostSetValue(int a)
{         
    Debug.WriteLine(a); //here I will use the value       
}

但我收到此错误:“加载资源失败:服务器响应状态为 500 () [https://localhost:44350/MyPage]”

我知道这可能不是这样做的方法,但我只找到了 MVC 的示例。有什么方法可以在 Asp.Net Core 中做到这一点?

【问题讨论】:

  • 您可以在查询字符串中传递值 a。我的意思是网址
  • 你的意思是不是像:url: './MyPage?i
  • 是的。你没看错
  • 但我仍然收到同样的错误,状态为 500
  • 你用过FromUrl吗?

标签: c# asp.net-core


【解决方案1】:

但我收到此错误:“加载资源失败:服务器 响应状态为 500 () [https://localhost:44350/MyPage]"

您可以在带有 Razor 页面的 Asp.Net Core 中做到这一点。

首先,ajax 中的url 中没有指定具体的post method name

其次,在Razor Pages中使用ajax传参有一个特殊要求,必须自己提供防伪令牌,也就是说我们需要添加@Html.AntiForgeryToken() 在您的页面视图中,然后在 ajax 中添加 headers 以传递防伪令牌。

更多详情请参考this

这是完整的例子:

@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>
}

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 2018-03-30
    • 2020-12-04
    • 2018-02-17
    • 2018-10-29
    • 2019-11-05
    • 2020-09-28
    • 2018-10-31
    • 1970-01-01
    相关资源
    最近更新 更多