.NET CORE Razor页面Ajax调用c#方法

时间:2022-09-05 03:17:25

I am currently making a site to display locations on a google map. I get the location addresses from an Airtable.com database and everything there is working fine. However because google only allow a certain number of request to geocode addresses, i want to save the coordinates in the same database, so i only use the geocode api when a new location(address) needs to be looked up. I got that all setup, but i can't seem to figure out how i call a cs method from js in razor pages. I have used WebMethod in the past but i can't use that here apparently.

我目前正在制作一个网站,在谷歌地图上显示位置。我从Airtable.com数据库中获取地址,那里的一切都运行得很好。但是,由于谷歌只允许对地理编码地址进行一定数量的请求,所以我想将坐标保存在同一个数据库中,所以只在需要查找新位置(地址)时使用地理编码api。我得到了所有的设置,但我似乎不知道如何从razor页面的js中调用cs方法。我以前用过WebMethod,但是这里显然不能用。

When i try to use the examples i find online, it says i need the RequestVerificationToken, but that needs the call to come from within a form(am i right?), and my ajax call is prompted when the site loads and it gets a location from the database which does not have any coordinates yet.

当我尝试使用我在网上找到的示例,它说我需要RequestVerificationToken,但需要调用来自在一个表单(对吗?),我的ajax调用是促使当网站负载,它从数据库中得到一个位置没有任何坐标。

This is my first time using Razor Pages, so bear with me if i have totally misunderstood something.

这是我第一次使用剃须刀片,如果我完全误解了的话,请原谅我。

Picture of my cs method i would like to call (Index.cshtml.cs) I tried with the httpPost tag, but it didn't make a difference

我想要调用的cs方法的图片(Index.cshtml.cs)我尝试使用httpPost标记,但没有什么区别

    [HttpPost] // RequestVerificationToken
    public void OnPostGeoLocation()
    {
        // Just to test that it actually gets called
        Console.WriteLine("OnPostGeoLocation CALLED ####################################");
        Console.WriteLine("OnPostGeoLocation CALLED ####################################");
        Console.WriteLine("OnPostGeoLocation CALLED ####################################");
        Console.WriteLine("OnPostGeoLocation CALLED ####################################");
    }

Picture of Ajax call from JavaScript, which is called on page load basically: AjaxCall

从JavaScript调用Ajax调用的图片,基本上是页面加载:AjaxCall。

function updateRow(recordID, latLng) {
   console.log("REC_ID: " + recordID);
   console.log("LatLng: " + latLng);
   $.ajax({
       type: "POST",
       url: '/Index?OnPostGeoLocation', 
       contentType: "application/json; charset=utf-8",
       dataType: "json"
   }).done(function (data) {
       console.log(data.result);
   })
 }

Im aware that some of the code is not exactly what i need, but i just copied from online and will edit when im ahead of this hurdle .

我知道有些代码并不是我所需要的,但我只是从网上拷贝,当我超越这个障碍时,我会进行编辑。

2 个解决方案

#1


2  

Try returning a proper IActionResult result.

尝试返回一个适当的IActionResult结果。

[HttpPost]
public IActionResult OnPostGeoLocation() {
    // Just to test that it actually gets called
    Console.WriteLine("OnPostGeoLocation CALLED ####################################");

    return new JsonResult("OnPostGeoLocation CALLED ####################################");
}

Next when making the call you need to call the correct handler path and include the anti-forgery token becasue, Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks.

接下来,当您需要调用正确的处理程序路径并包含反伪造令牌becasue时,Razor页面被设计为自动保护,避免跨站点请求伪造(CSRF/XSRF)攻击。

Updated Ajax call

更新的Ajax调用

function updateRow(recordID, latLng) {
    console.log("REC_ID: " + recordID);
    console.log("LatLng: " + latLng);
    $.ajax({
        type: "POST",
        url: '/Index?handler=GeoLocation', 
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {
        console.log(data.result);
    })
}

Very helpful article for reference

非常有用的文章供参考

Handle Ajax Requests in ASP.NET Core Razor Pages

在ASP中处理Ajax请求。网络核心剃刀页面

#2


1  

After reading Handle Ajax Requests in ASP.NET Core Razor Pages more carefully i figured out that i had indeed misunderstood some of the principles and that you CAN add AntiForgeryToken explicitly without a "form" tag, using @Html.AntiForgeryToken()

阅读后,在ASP中处理Ajax请求。我更仔细地发现,我确实误解了一些原则,您可以使用@Html.AntiForgeryToken()来显式地添加反forgerytoken,而不使用“form”标记。

My code look like this now: .NET CORE Razor页面Ajax调用c#方法

我的代码现在是这样的:

And:

和:

.NET CORE Razor页面Ajax调用c#方法

#1


2  

Try returning a proper IActionResult result.

尝试返回一个适当的IActionResult结果。

[HttpPost]
public IActionResult OnPostGeoLocation() {
    // Just to test that it actually gets called
    Console.WriteLine("OnPostGeoLocation CALLED ####################################");

    return new JsonResult("OnPostGeoLocation CALLED ####################################");
}

Next when making the call you need to call the correct handler path and include the anti-forgery token becasue, Razor Pages are designed to be automatically protected from cross-site request forgery (CSRF/XSRF) attacks.

接下来,当您需要调用正确的处理程序路径并包含反伪造令牌becasue时,Razor页面被设计为自动保护,避免跨站点请求伪造(CSRF/XSRF)攻击。

Updated Ajax call

更新的Ajax调用

function updateRow(recordID, latLng) {
    console.log("REC_ID: " + recordID);
    console.log("LatLng: " + latLng);
    $.ajax({
        type: "POST",
        url: '/Index?handler=GeoLocation', 
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {
        console.log(data.result);
    })
}

Very helpful article for reference

非常有用的文章供参考

Handle Ajax Requests in ASP.NET Core Razor Pages

在ASP中处理Ajax请求。网络核心剃刀页面

#2


1  

After reading Handle Ajax Requests in ASP.NET Core Razor Pages more carefully i figured out that i had indeed misunderstood some of the principles and that you CAN add AntiForgeryToken explicitly without a "form" tag, using @Html.AntiForgeryToken()

阅读后,在ASP中处理Ajax请求。我更仔细地发现,我确实误解了一些原则,您可以使用@Html.AntiForgeryToken()来显式地添加反forgerytoken,而不使用“form”标记。

My code look like this now: .NET CORE Razor页面Ajax调用c#方法

我的代码现在是这样的:

And:

和:

.NET CORE Razor页面Ajax调用c#方法