My main view is able to plot data in DataTable. There is a button to save the entire table to database. But I am unable to send this entire table to my Controller's ActionResult. Here is my Codes: -
User_Auth_List.cshtml
@model IList<IDESK.Models.UserMaster.ModuleMaster>
@using IDESK.Models.UserMaster;
<!DOCTYPE html>
<div id="modal-placeholder"></div>
@Html.AntiForgeryToken()
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>User_Rights_List</title>
</head>
<body class="hold-transition sidebar-mini">
<form id="frmDetails">
<div class="wrapper" id="mainbody">
<h4 style="color:indigo">User Rights Index</h4>
<button type="button" id="saveButton">Save</button>
<div class="form-inline" style="margin-top:5px">
<label class="col-form-label" style="margin-left:150px; margin-right:15px;color:black;">Select User</label>
<select class="form-control col-sm-2" style="width: 300px;" id="ddlUser" name="UserId" asp-items="@(new SelectList(ViewBag.UserList, "Value", "Text"))">
<option value="">-User-</option>
</select>
<input type="hidden" name="UserId" />
</div>
@**@
<input type="hidden" name="action" value="Create" />
<div id="tblUserAuthDV">
@await Html.PartialAsync("_TblUser_Auth_List", Model)
</div>
</div>
@{
if (TempData["Message"] != null)
{
<div class="row">
<div class="col-md-12">
<div class="form-group">
@Html.Raw(TempData["Alert"])
</div>
</div>
</div>
}
}
</form>
</body>
</html>
<link href="~/lib/select2/css/select2.css" rel="stylesheet" />
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/twitter-bootstrap/js/bootstrap.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="~/lib/select2/js/select2.js"></script>
@section Scripts
{
<partial name="_ValidationScriptsPartial" />
<script>
$(document).ready(function () {
var userid = $(this).find("option:selected").val();
var placeholderElement = $('#modal-placeholder');
$(document).on('click', 'button[data-bs-toggle="ajax-modal"]', function (event) {
$("#btnUserRights").html(' Saving...');
document.getElementById("btnUserRights").disabled = true;
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
$('.modal').draggable();
TouchPopUp();
});
});
placeholderElement.on('click', '[data-bs-dismiss="modal"]', function (event) {
$("#btnUserRights").html(' Save User Rights');
document.getElementById("btnUserRights").disabled = false;
});
placeholderElement.on('shown.bs.modal', function (e) {
$("#btnUserRights").html('^__i class="fa fa-plus"> Save User Rights');
});
placeholderElement.on('click', '[data-bs-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var dataToSend = new FormData(form.get(0));
$.ajax({ url: actionUrl, method: 'post', data: dataToSend, processData: false, contentType: false }).done(function (data) {
var newBody = $('.modal-body', data);
placeholderElement.find('.modal-body').replaceWith(newBody);
var isValid = newBody.find('[name="IsValid"]').val() === 'True';
if (isValid) {
var notificationsPlaceholder = $('#notification');
var notificationsUrl = notificationsPlaceholder.data('url');
$.get(notificationsUrl).done(function (notifications) {
notificationsPlaceholder.html(notifications);
});
var tableElement = $('#tblUserAuthList');
var tableUrl = tableElement.data('url');
$.get(tableUrl).done(function (table) {
tableElement.replaceWith(table);
});
placeholderElement.find('.modal').modal('hide');
alert("Success : Document Saved !");
}
else {
alert("Error : Document did not Save !");
}
$("#btnUserRights").html(' Create User Rights');
document.getElementById("btnUserRights").disabled = false;
});
});
})
$('#saveButton').click(function () {
var tableData = [];
$("#tblUserAuthList tr:not(:first)").each(function () {
var row = $(this);
var data = {
UserId: row.find('input[name="UserId"]').val(),
Module_Group: row.find('input[name="Module_Group"]').val(),
ModuleID: row.find('input[name="ModuleID"]').val(),
Module_Name: row.find('input[name="Module_Name"]').val(),
IsAccess: row.find('input[name="IsAccess"]').val(),
IsCreate: row.find('input[name="IsCreate"]').val(),
IsDelete: row.find('input[name="IsDelete"]').val(),
IsView: row.find('input[name="IsView"]').val(),
IsReport: row.find('input[name="IsReport"]').val()
};
tableData.push(data);
});
var formData = {
UserId: $('#ddlUser').val(),
tableData: tableData,
action: "Create"
};
$.ajax({
url: '/UserRights/Create',
type: 'POST',
cache: false,
data: tableData,
contentType: "application/json; charset=utf-8",
success: function (response) {
},
error: function (xhr, status, error) {
console.log(formData);
alert(xhr, status, error);
}
});
});
$('#ddlUser').select2({
placeholder: "UserId",
allowClear: true,
theme: "classic",
dropdownPosition: 'below'
});
$("body").on("change", "#ddlUser", function () {
$("input[name=UserId]").val($(this).find("option:selected").text());
var userid = $(this).find("option:selected").val();
$.ajax
({
url: '/UserRights/Auth_List',
data: { 'id': userid },
type: "GET",
cache: false,
success: function (result) {
$("#tblUserAuthDV").html(result)
}
});
$("#tblUserAuthDV").show();
});
</script>
}
Partial View to Generate Table : tblUserAuthList.cshtml
@model IEnumerable<IDESK.Models.UserMaster.ModuleMaster>
<table id="tblUserAuthList" class="table table-responsive table-condensed table-fixedheader table-hover" style="table-layout:fixed; width:fit-content; white-space: nowrap; max-height: 500px; margin-top: 10px;">
<thead>
<tr>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).UserId)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).Module_Group)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).ModuleID)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).Module_Name)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).IsAccess)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).IsCreate)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).IsEdit)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).IsDelete)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).IsView)
</th>
<th style="color:white;">
@Html.DisplayNameFor(model => model.ElementAt(0).IsReport)
</th>
</tr>
</thead>
<tbody style="background-color: white;">
@{
if (Model != null && Model.Count() > 0 )
{
@for (int i=0; i<Model.Count();i++)
{
<tr>
<td style="color:black;">
@Html.DisplayFor(item => item.ElementAt(i).UserId)
@Html.HiddenFor(x => x.ElementAt(i).UserId)
</td>
<td style="color:black;">
@Html.DisplayFor(item => item.ElementAt(i).Module_Group)
@Html.HiddenFor(x => x.ElementAt(i).Module_Group)
</td>
<td style="color:black;">
@Html.DisplayFor(item => item.ElementAt(i).ModuleID)
@Html.HiddenFor(x => x.ElementAt(i).ModuleID)
</td>
<td style="color:black;">
@Html.DisplayFor(item => item.ElementAt(i).Module_Name)
@Html.HiddenFor(x => x.ElementAt(i).Module_Name)
</td>
<td style="color:black;">
@Html.EditorFor(item => item.ElementAt(i).IsAccess)
</td>
<td style="color:black;">
@Html.EditorFor(item => item.ElementAt(i).IsCreate)
</td>
<td style="color:black;">
@Html.EditorFor(item => item.ElementAt(i).IsEdit)
</td>
<td style="color:black;">
@Html.EditorFor(item => item.ElementAt(i).IsDelete)
</td>
<td style="color:black;">
@Html.EditorFor(item => item.ElementAt(i).IsView)
</td>
<td style="color:black;">
@Html.EditorFor(item =>item.ElementAt(i).IsReport)
</td>
</tr>
}
}
}
</tbody>
</table>
<script type="text/javascript">
function Save() {
$.ajax({
type: 'POST',
url: '@Url.Action("Create")',
data: $("#frm_User_Auth").serialize(),
success: function (data) {
alert(data);
$('.tampil_vr').text(data);
}
});
}
$(document).ready(function () {
$("#tblUserAuthList").DataTable({ stateSave: true, async: false });
});
</script>
My Controller : UserRightsController.cs
using IDESK.Models.UserMaster;
using IDESK.Models;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Rendering;
using DocumentFormat.OpenXml.Wordprocessing;
using IDESK.Models.Customer;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Office2021.PowerPoint.Comment;
using Microsoft.AspNetCore.Http;
namespace IDESK.Controllers.UserMaster
{
public class UserRightsController : Controller
{
private readonly DbConn _dbConn;
public static List<User_Auth> user_auth = new();
public static List<ModuleMaster> moduleMasters = new();
public UserRightsController(DbConn db)
{
_dbConn = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Auth_List(string id)
{
try
{
DDLUserList();
var isAjax = Request.Headers["X-Requested-With"] == "XMLHttpRequest";
if (isAjax)
{
var ModuleList = from a in _dbConn.Modules
from c in _dbConn.UserAuth.Where(c => c.UserId == id)
join b in _dbConn.Module_Group on a.GroupID equals b.GroupID
into modulegroup
from b in modulegroup.DefaultIfEmpty()
select new ModuleMaster
{
UserId = id,
Module_Group = b.Module_Group,
ModuleID = a.ModuleID,
Module_Name = a.Module_Name,
GroupID = a.GroupID,
IsAccess = a.ModuleID == c.ModuleID ? c.IsAccess : false,
IsCreate = a.ModuleID == c.ModuleID ? c.IsCreate : false,
IsDelete = a.ModuleID == c.ModuleID ? c.IsDelete : false,
IsEdit = a.ModuleID == c.ModuleID ? c.IsEdit : false,
IsReport = a.ModuleID == c.ModuleID ? c.IsReport : false,
IsView = a.ModuleID == c.ModuleID ? c.IsView : false,
};
if(ModuleList.Count() <=0)
{
ModuleList = from a in _dbConn.Modules
join b in _dbConn.Module_Group on a.GroupID equals b.GroupID
into modulegroup
from b in modulegroup.DefaultIfEmpty()
select new ModuleMaster
{
UserId = id,
Module_Group = b.Module_Group,
ModuleID = a.ModuleID,
Module_Name = a.Module_Name,
GroupID = a.GroupID,
IsAccess = false,
IsCreate = false,
IsDelete = false,
IsEdit = false,
IsReport = false,
IsView = false,
};
}
return PartialView("_TblUser_Auth_List", ModuleList);
}
return View("User_Auth_List", null);
}
catch (Exception ex)
{
return View();
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(IList<ModuleMaster> collection, string action,string UserID)
{
DDLUserList();
return View("User_Auth_List", collection);
}
private JsonResult DDLUserList()
{
try
{
var UserList = _dbConn.UserMaster.Select(x => new
{
Text = String.Format("{0,-10} : {1}", x.UserId, x.DisplayName),
Value = x.UserId
}).ToList();
ViewBag.UserList = new SelectList(UserList, "Value", "Text");
return Json(UserList);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
My Model : ModuleMaster.cs
<pre lang="C#">using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace IDESK.Models.UserMaster
{
public class ModuleMaster
{
[Key]
public int ModuleID { get; set; }
[Required]
public string Module_Name { get; set; }
[Required]
public int GroupID { get; set; }
[NotMapped]
[Required(ErrorMessage = "??")]
[Display(Name = "User ID")]
public string UserId { get; set; }
[NotMapped]
[Display(Name = "Access")]
public bool IsAccess { get; set; }
[NotMapped]
[Display(Name = "Delete")]
public bool IsDelete { get; set; }
[NotMapped]
[Display(Name = "Create")]
public bool IsCreate { get; set; }
[NotMapped]
[Display(Name = "Edit")]
public bool IsEdit { get; set; }
[NotMapped]
[Display(Name = "View")]
public bool IsView { get; set; }
[NotMapped]
[Display(Name = "Report")]
public bool IsReport { get; set; }
[NotMapped]
public string DisplayName { get; set; }
[NotMapped]
public string Department { get; set; }
[NotMapped]
public string Module_Group { get; set; }
}
}
What I have tried:
Uses List or IList instead of IEnumerable<t>, For() loop instead of ForEach()
And 'SUBMIT' form instead of Button click event.