简体   繁体   English

Asp.net Core 2.0 Razor Pages Ajax Post

[英]Asp.net Core 2.0 Razor Pages Ajax Post

I am trying to just jquery ajax call to retrieve a list of users from a Razor page. 我试图只是jquery ajax调用从Razor页面检索用户列表。

Users.cshtml.cs page: Users.cshtml.cs页面:

public ActionResult OnPostList(string FirstName, string LastName,string IsActive)
{
        var data=(from s in _db.SecurityUser
                 where s.FirstName.Contains(FirstName) && s.LastName.Contains(LastName) && (IsActive=="" || (IsActive =="Y" && s.IsActive==true) || (IsActive == "N" && s.IsActive == false))
                 select s).OrderBy(s=>s.FirstName);
        return new JsonResult(data);
}

JS Call: JS电话:

$.ajax({
    type: "POST",
    url: "/Security/Users?handler=List",
    data: JSON.stringify({
        FirstName: $("#txtFirstName").val(),
        LastName: $("#txtLastName").val(),
        IsActive: $("#ddActive").val()
    }),
    contentType: "application/json",
    dataType: "json",
    success: function (response) {
        var d = response.d;
        var tblBody = $("#tblUsers > tbody");
        tblBody.empty();
        $.each(d, function (i, item) {
            var modifiedDate = new Date(parseInt(item.ModifiedDate.substr(6)));
            var $tr = $('<tr>').append(
                $('<td>').html("<a href='javascript:void(0)' onclick='fnDialogShow(" + item.UserID + ")'>Edit</a>"),
                $('<td>').text(item.FirstName),
                $('<td>').text(item.LastName),
                $('<td>').text(item.IsActive ? "Yes" : "No")
            ).appendTo(tblBody);

        });
    },
    failure: function (response) {
        alert(response.d);
    }

});

When it calls I get a 400 error back. 当它调用时我得到400错误。 Trying to figure out what I am doing wrong. 试图找出我做错了什么。

Your URL formation for Ajax request is correct. 您的Ajax请求的URL格式是正确的。 One thing to note down is, Razor Pages are designed to be protected from (CSRF/XSRF) attacks. 需要注意的一点是,Razor Pages旨在保护(CSRF / XSRF)攻击。 Hence, Antiforgery token generation and validation are automatically included in Razor Pages. 因此,Antiforgery令牌生成和验证将自动包含在Razor Pages中。 I believe that is the problem here. 我相信这就是问题所在。 Your page may have antiforgery token present on the page if you have form tag in your HTML. 如果您的HTML中有表单标记,则您的页面可能会在页面上显示防伪令牌。 But you need to pass the same in your Ajax request. 但是您需要在Ajax请求中传递相同的内容。

First, add antiforgery token using @Html.AntiForgeryToken() , if not present. 首先,使用@Html.AntiForgeryToken()添加防伪令牌@Html.AntiForgeryToken()如果不存在)。

Then, modify your Ajax request to send the same in request header. 然后,修改您的Ajax请求以在请求标头中发送相同的内容。

Like, 喜欢,

 beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); }, 

Read this post Handle Ajax Requests in ASP.NET Core Razor Pages to know more about making ajax request with ASP.NET Core razor pages. 阅读此文章处理ASP.NET Core Razor页面中的Ajax请求,以了解有关使用ASP.NET Core razor页面发出ajax请求的更多信息。

By default, Razor Pages are designed to be protected CSRF attacks. 默认情况下,Razor Pages旨在保护CSRF攻击。

You must properly inject the antiforgery token into your ajax request. 您必须正确地将防伪令牌注入您的ajax请求中。

See the Documentation. 请参阅文档。

In ASP.NET Core 2.0 it looks like this... 在ASP.NET Core 2.0中它看起来像这样......

First place this code into the top of your razor view: 首先将此代码放入剃刀视图的顶部:

// At the top of your page
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@functions{
    public string GetAntiXsrfRequestToken()
    {
        return Xsrf.GetAndStoreTokens(Context).RequestToken;
    }
}

Then in your ajax request, set the token header. 然后在您的ajax请求中,设置令牌标头。

$.ajax({
    type: "post",
    headers: {
        "RequestVerificationToken": '@GetAntiXsrfRequestToken()'
    },
    url: '@Url.Action("Antiforgery", "Home")',
    success: function (result) {
        alert(result);
    },
    error: function (err, scnd) {
        alert(err.statusText);
    }
});

for .net core 2.1 the solution from this blog helped https://www.thereformedprogrammer.net/asp-net-core-razor-pages-how-to-implement-ajax-requests/ for .net core 2.1此博客的解决方案帮助https://www.thereformedprogrammer.net/asp-net-core-razor-pages-how-to-implement-ajax-requests/

if the page does not contain form with method post, add antiforgery token @Html.AntiForgeryToken() 如果页面不包含带有方法帖子的表单,请添加防伪令牌@Html.AntiForgeryToken()

and you can start to fire ajax request, important part is to set headers here. 你可以开始激活ajax请求,重要的是在这里设置标题

$.ajax({
                type: "POST",
                url: "/Customers?handler=Delete",
                data: { id: id },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                // AntiforgeryToken is required by RazorPages
                headers: {
                    RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
                }
            })
            .done(function () {
                alert("success");
            })
            .fail(function () { 
                alert("error");
            });

使用HttpPost属性标记您的OnPostList,并在ajax调用中将您的URL更改为/ Security / OnPostList

add [HttpPost] in Action 在Action中添加[HttpPost]

  [HttpPost]
    public ActionResult OnPostList(string FirstName, string LastName,string IsActive)
    {
            var data=(from s in _db.SecurityUser
                     where s.FirstName.Contains(FirstName) && s.LastName.Contains(LastName) && (IsActive=="" || (IsActive =="Y" && s.IsActive==true) || (IsActive == "N" && s.IsActive == false))
                     select s).OrderBy(s=>s.FirstName);
            return new JsonResult(data);
    }

Used this Script in Users.cshtml.cs Users.cshtml.cs使用此Script

<script>
  var url='@(Url.Action("OnPostList","ControllerName"))';
  var firstName= $("#txtFirstName").val();
  var lastName= $("#txtLastName").val();
  var isActive= $("#ddActive").val();
  $.post(Url,{FirstName:firstName,LastName=lastName,IsActive=isActive},function(data){
      var d = data.d;
      var tblBody = $("#tblUsers > tbody");
      tblBody.empty();
      $.each(d, function (i, item) {
         var modifiedDate = new Date(parseInt(item.ModifiedDate.substr(6)));
         var $tr = $('<tr>').append(
         $('<td>').html("<a href='javascript:void(0)' onclick='fnDialogShow(" + item.UserID + ")'>Edit</a>"),
         $('<td>').text(item.FirstName),
         $('<td>').text(item.LastName),
         $('<td>').text(item.IsActive ? "Yes" : "No")
         ).appendTo(tblBody);
       });
    });
</script>

I had bad experiences with $.ajax, I used $.post instead. 我使用$ .ajax遇到了不好的经历,我使用了$ .post。 I used validateAntiforgeryToken but its not necessary 我使用了validateAntiforgeryToken,但没有必要

    $("#emailSubmit").click(function () {

        $.post("/Projects/SendInvite",
            {
                Email: $("#email").val(),
                Message: $("#message").val(),
                __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
            }

        )
        return false;

    });

And this is net core action: 这是净核心行动:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult SendInvite(string Email, string Message)
{

        //MailTest();
        var json = new List<string>
        {
        Email,
        Message
        };
        return new JsonResult(json);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM