衫裤跑路 2020-03-12 23:54 采纳率: 50%
浏览 140

使用AJAX删除Razor Pages

I'm trying to figure out using AJAX with Razor Pages.

I've been searching the Web but each example I've found does something different, and most are incomplete or not for Razor Pages.

So far, I've been focusing on variations of something like this:

$.post('/?handler=Delete', 5, function (x) {
    alert(x);
});

And then my page model looks like this:

public void OnPostDelete(int id)
{

}

I've tried variations on this but, so far, my C# code is not getting called.

Questions:

  • Can someone show me what I'm missing?
  • Can anyone offer some good references for this? (I need to perform other AJAX tasks as well.)
  • Some examples I found had special handling related to anti-forgery tokens. Do I need to code for that as well?

UPDATE:

So I've been working with this and this is what I have now:

$.ajax({
    url: '?handler=Delete',
    data: {
        id: $(this).data('id')
    }
})
.fail(function (e) {
    // Error
    alert(e.responseText); // Way too much info
})
.done(function () {
    // Success
})
.always(function () {
    // Always
});

And my handler:

public void OnGetDelete(int id)
{

}

This is in fact calling my handler and I finally got it to pass the id argument.

Since I have a bounty, here's what I'd like to see in an answer:

  1. If I set the AJAX call to use POST and rename my handler to OnPostDelete(), the handler is not called. How would I do a post?
  2. Any other suggestions or criticisms with the code above? I know there are many ways to do this. I'm just looking for the simplest way and trying to refine it.
  • 写回答

4条回答

  • weixin_33691700 2020-03-13 01:39
    关注

    Two suggestion:

    1- add the page path in front of the url. (I am not sure if it is mentioned in your words).

    $.post('/{page_path}/?handler=Delete', 5, function (x) {
        alert(x);
    });
    

    2- Follow the route map rule. For example, there is the 'id' in your function. The page may have configured like @page "{id:int}". So the url should be something like

    $.post('/{page_path}/{id}/?handler=Delete', 5, function (x) {
        alert(x);
     });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 为什么树莓派5b显示禁止连接
  • ¥20 流量太费!寻找便宜的app音视频SDK或平替方案。
  • ¥15 kubeasz部署遇到问题
  • ¥15 GUIDE to App Designer Migration Tool for MATLAB
  • ¥50 第三代非支配排序遗传算法(NSGA-Ⅲ)和多目标粒子群优化算法(MOPSO)的实现
  • ¥20 plant simulation与python com接口实时数据交互
  • ¥15 有关汽车的MC9S12XS128单片机实验
  • ¥15 求c语言动态链表相关课程有偿,或能将这块知识点讲明白
  • ¥15 FLKT界面刷新异常
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证