asp.net core razor pages web项目大部分情况下使用继承与pagemodel中的方法直接调用就可以(asp-page),但是有些时候需要使用ajax调用,更方便些。那么如何使用ajax调用呢??

1.razor pages普通页面的跳转

<a asp-page="about">about</a>
<form asp-page="./index" method="get">
    <div class="form-actions no-color">
        <p>
            find by name:
            <input type="text" name="searchstring" value="@model.currentfilter" />
            <input type="submit" value="search" class="btn btn-primary" />|
            <a asp-page="./index">back to full list</a>
        </p>
    </div>
</form>

form默认为post提交,asp-page跳转的页面,首先获取的是get方法,如:ongetasync或者onget,同时存在运行会报错

2. 针对一个页面的多个按钮处理

<form method="post">
    <div>name: <input asp-for="customer.name" /></div>
    <input type="submit" asp-page-handler="joinlist" value="join" />
    <input type="submit" asp-page-handler="joinlistuc" value="join uc" />
</form>

指向当前页面的joinlist方法和joinlistuc方法,增加了handle,将跳转到onpost[handler]async方法。

3. razor pages中ajax的get使用

$.get("?handler=filter", { id: $(this).attr("data-id") },
    function (result) {
        console.log(result);
});
$.ajax({
    type: 'get',
    contenttype: "application/json",
    datatype: "json",
    url: "?handler=filter",
    success: function (result) {
        alert(result);
    }
});

跳转到ongetfilterasync方法,url写的需要注意(handler=)就可以了

4. razor pages中ajax的post使用

razor pages 由防伪造验证保护,formtaghelper 将防伪造令牌注入 html 窗体元素,防止跨站点请求伪造 (xsrf/csrf)。
xss:跨站脚本(cross-site scripting,通常简称为xss)是一种网站应用程序的安全漏洞攻击,是代码注入的一种。它允许恶意用户将代码注入到网页上,其他用户在观看网页时就会受到影响。这类攻击通常包含了html以及用户端脚本语言。
csrf:跨站请求伪造(英语:cross-site request forgery),也被称为 one-click attack 或者 session riding,通常缩写为 csrf 或者 xsrf, 是一种挟制用户在当前已登录的web应用程序上执行非本意的操作的攻击方法。
由于以上的问题,直接ajax post请求会出错,错误这里就不贴图了。

解决办法1:推荐

1. ***.cshmtl你的页面增加

@html.antiforgerytoken()

2. ajax post请求

$.ajax({
    url: '?handler=filter2',
    type: 'post',
    contenttype: 'application/x-www-form-urlencoded',
    data: {"__requestverificationtoken":$('input:hidden[name="__requestverificationtoken"]').val()},
    success: function (result) {
        alert(result);
    }
});

 

解决办法2:

1. startup.cs中的configureservices方法增加

services.addantiforgery(o => o.headername = "xsrf-token");

2. ***.cshmtl你的页面增加

@html.antiforgerytoken()

3. ajax post请求

$.ajax({
    url: '?handler=filter2',
    type: 'post',
    contenttype: 'application/json; charset=utf-8',
    headers: {
        "xsrf-token":$('input:hidden[name="__requestverificationtoken"]').val() 
    },
    success: function (result) {
        alert(result);
    }
});

解决方法3:不推荐

1. startup.cs中的configureservices方法增加

services.addrazorpages().addrazorpagesoptions(o=> { o.conventions.configurefilter(new ignoreantiforgerytokenattribute()); });

2. ajax post请求

$.ajax({
    url: '?handler=filter2',
    type: 'post',
    contenttype: 'application/json; charset=utf-8',
    success: function (result) {
        alert(result);
    }
});