Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Users.cshtml.cs page:

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:

$.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. Trying to figure out what I am doing wrong.

like image 892
Jason Webber Avatar asked Oct 18 '17 23:10

Jason Webber


People also ask

What is the use of razor pages in asp net core?

Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views. If you're looking for a tutorial that uses the Model-View-Controller approach, see Get started with ASP.NET Core MVC. This document provides an introduction to Razor Pages. It's not a step by step tutorial.

What is ViewData razor pages?

ViewData is a container for data to be passed from the PageModel to the content page. ViewData is a dictionary of objects with a string-based key. You add items to ViewData as follows: public class IndexModel : PageModel.


1 Answers

Your URL formation for Ajax request is correct. One thing to note down is, Razor Pages are designed to be protected from (CSRF/XSRF) attacks. Hence, Antiforgery token generation and validation are automatically included in 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. But you need to pass the same in your Ajax request.

First, add antiforgery token using @Html.AntiForgeryToken(), if not present.

Then, modify your Ajax request to send the same in request header.

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.

like image 192
VirendraJ Avatar answered Oct 07 '22 13:10

VirendraJ