I am trying to pass the ListOfUserModel data to class(NewUser.cshtml) from the rajor page(NewUser.cshtml) but always getting 0 records. I am adding the records in the table and trying to pass those records to the class on click of submit button. Can anyone please help me to understand what I am doing wrong here?
Sample HTML Page
NewUser.cshtml
@page
@model NewUserModel
@{
ViewData["Title"] = "New User";
}
<h5 style="margin-left: 15px;">Request New Users</h5>
<div >
<div >
<div >
<form id="request-form" method="post">
<div style="margin-bottom: 15px;">
<label for="inputWorkload">Workload</label>
<div >
<input type="text" value="" id="inputWorkload" placeholder="Workload" asp-for="NewUser.Workload">
</div>
</div>
<div id="userDiv">
<div style="margin-bottom: 15px;">
<label for="inputName">Name</label>
<div >
<input type="text" value="" id="inputName" placeholder="Name" asp-for="NewUser.Name">
</div>
</div>
</div>
<p aria-hidden="true" id="required-description">
<span > </span> Required field
</p>
<p id="entry-error">@Model.Error</p>
<div style="margin-bottom: 15px;width: fit-content;cursor: pointer;" onclick="AddUserRecords()">
<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" viewBox="0 0 16 16" style="width: fit-content;">
<path d="M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z" />
<path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z" />
</svg> Add User
</div>
<table style="width: 100%;" id="tableUserRecord">
<thead>
<tr>
<th>
Workload
</th>
<th>
Name
</th>
</tr>
</thead>
</table>
<div style="float: right; padding-top: 10px;">
<button type="button" id="btnClearData" onclick="clearForm()">Clear</button>
<button type="submit" id="btnSubmitData" >Submit</button>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#btnSubmitData").click(function () {
SubmitData();
});
});
function AddUserRecords() {
var userRecord = "<tr><td>" $("#inputWorkload").val() "</td><td>" $("#inputName").val() "</td></tr>";
$("#tableUserRecord").last().append(userRecord);
$("#inputName").val("");
}
function SubmitData() {
var ListOfUserModel = new Array();
$("#tableUserRecord").find("tr:gt(0)").each(function () {
var Workload = $(this).find("td:eq(0)").text();
var Name = $(this).find("td:eq(1)").text();
@*alert(Workload " " Name);*@
var UserModel = {};
UserModel.Workload = Workload;
UserModel.Name = Name;
ListOfUserModel.append(UserModel);
});
}
</script>
NewUser.cshtml.cs
using Tool.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Tool.Pages
{
public class NewUserModel : PageModel
{
[BindProperty]
public UserModel NewUser { get; set; }
[BindProperty]
public List<UserModel> ListOfUserModel { get; set; }
[BindProperty(SupportsGet = true)]
public string? Error { get; set; }
public void OnGet()
{
}
public IActionResult OnPost(IEnumerable<UserModel> ListOfUserModel)
{
try
{
}
catch (Exception ex)
{
return RedirectToPage("/NewUser", new { Error = "An error occoured" });
}
}
}
}
UserModel.cs
namespace Tool.Models
{
public class UserModel
{
public int id { get; set; }
public string? Name { get; set; }
public string? Workload { get; set; }
}
}
CodePudding user response:
1.You use type="submit"
button without using e.preventDefault();
which caused do not hit SubmitData
function.
2.Your SubmitData
function add the json array ListOfUserModel
but do not even use it.
3.The js Array does not contain .append
function. You need use .push
.
Two ways can achive your requirement:
First way of using ajax
@section Scripts
{
<script>
$(document).ready(function () {
$("#btnSubmitData").click(function (e) {
e.preventDefault(); //add this....
SubmitData();
});
});
function AddUserRecords() {
var userRecord = "<tr><td>" $("#inputWorkload").val() "</td><td>" $("#inputName").val() "</td></tr>";
$("#tableUserRecord").last().append(userRecord);
$("#inputName").val("");
}
function SubmitData() {
var ListOfUserModel = new Array();
$("#tableUserRecord").find("tr:gt(0)").each(function () {
var Workload = $(this).find("td:eq(0)").text();
var Name = $(this).find("td:eq(1)").text();
var UserModel = {};
UserModel.Workload = Workload;
UserModel.Name = Name;
ListOfUserModel.push(UserModel); //modify here....
});
console.log(ListOfUserModel)
//add ajax...
$.ajax({
url: "/NewUser",
type: 'post',
contentType: "application/json; charset=utf-8",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: JSON.stringify(ListOfUserModel),
success: function() {
//do your stuff after callback
}
})
}
</script>
}
Add [FromBody]
to OnPost:
public IActionResult OnPost([FromBody]IEnumerable<UserModel> ListOfUserModel)
{
try
{
}
catch (Exception ex)
{
return RedirectToPage("/NewUser", new { Error = "An error occoured" });
}
}
The second way of using form submit
table elements cannot be posted to the backend by form submit, you need add the hidden input. Also only need AddUserRecords
function. SubmitData
function is useless.
@section Scripts
{
<script>
var count = 0; //add it.............
function AddUserRecords() {
//modify here...................
var userRecord = "<tr><td>" $("#inputWorkload").val() "<input value='" $("#inputWorkload").val() "' name='[" count "].Workload' hidden />" "</td><td>" $("#inputName").val() "<input value='" $("#inputName").val() "' name='[" count "].Name' hidden />" "</td></tr>";
$("#tableUserRecord").last().append(userRecord);
$("#inputName").val("");
count ; //add this.......
}
</script>
}
Backend:
public IActionResult OnPost(IEnumerable<UserModel> ListOfUserModel)
{
try
{
}
catch (Exception ex)
{
return RedirectToPage("/NewUser", new { Error = "An error occoured" });
}
}