I am trying to pass the ListOfUserModel data to class(UserRequests.cshtml.cs) from the rajor page(UserRequests.cshtml) but it always goes to error function of ajax and prompts the alert box. I am trying to pass the records of the specific row on click of APPROVE button to the class. Can anyone please help me to understand what I am doing wrong here?
UserRequests.cshtml
@page
@model UserRequestsModel
@{
Layout = "~/Pages/Shared/_LayoutAdmin.cshtml";
}
<h5>Users Requests</h5>
<br>
<table id="usersTable" style="width: 100%;">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Company Email</th>
<th style="width:20%">Approve/Deny</th>
</tr>
</thead>
<tbody>
@foreach(var user in Model.userList)
{
<tr>
<td>@user.id</td>
<td >@user.Name</td>
<td >@user.CompanyEmail</td>
<td>
<button type="submit" >Approve</button>
</td>
<td>
<button type="submit" >Deny</button>
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(".btnApprove").click(function () {
var ListOfUserModel = new Array();
var row = $(this).closest('tr');
var Name = row.find('.tdName').text();
var CompanyEmail = row.find('.tdCompanyEmail').text();
var UserModel = {};
UserModel.Name = Name;
UserModel.CompanyEmail = CompanyEmail;
ListOfUserModel.push(UserModel);
$.ajax({
url: "/Admin/UserRequests",
type: 'post',
contentType: "application/json; charset=utf-8",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: JSON.stringify(ListOfUserModel),
success: function (data) {
alert("Users Data Submitted Successfully");
},
error: function () {
alert("SOME PROB.");
}
});
});
</script>
UserRequests.cshtml.cs
using Tool.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Tool.Pages.Admin
{
public class UserRequestsModel : PageModel
{
[BindProperty]
public UserModel NewUser { get; set; }
public List<UserModel> userList = new List<UserModel>();
public void OnGet()
{
}
public IActionResult OnPost([FromBody]IEnumerable<UserModel> ListOfUserModel)
{
return null;
}
}
}
UserModel.cs
namespace Tool.Models
{
public class UserModel
{
public int id { get; set; }
public string? Name { get; set; }
public string? CompanyEmail { get; set; }
}
}
CodePudding user response:
You have used the value of __RequestVerificationToken
input
in your header, but this input is not present in your html code, and you receive an error due to not sending anti forgery token
, just put the following code in a part of your UserRequests.cshtml
File
@Html.AntiForgeryToken()
more info: What is Request Verification