Click here to Skip to main content
15,887,083 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
Razor
@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>
            @*<span asp-validation-for="model => model.UserId" style="margin-left:4px;" class="text-danger"></span>*@

            <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 () {

            // $("#tblUserAuthList").DataTable({ stateSave: true, });

            var userid = $(this).find("option:selected").val();

            //  $("#tblUserAuthDV").hide();

            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');
            });
            //alert("site");
            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 () {
            //$('#tblUserAuthDV table tr').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',
                //'@Url.Action("Create", "UserRights")',
                type: 'POST',
                cache: false,
                data: tableData, //JSON.stringify({Model : formData}),
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    // Handle the success response if needed
                },
                error: function (xhr, status, error) {
                    console.log(formData);
                    alert(xhr, status, error);
                    // Handle the error if needed
                }
            });
        });



        //----User List
        $('#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();

            //if (userid == "") {
            //    $("#tblUserAuthDV").hide();
            //}
            //else {
            $.ajax
                ({
                    url: '/UserRights/Auth_List',
                    data: { 'id': userid },
                    type: "GET",
                    cache: false,
                    success: function (result) {
                        $("#tblUserAuthDV").html(result)
                    }
                });
            $("#tblUserAuthDV").show();
            //}
        });
                    //var IsPallet = $(this).find("option:selected").text().search("True");
    </script>

}


Partial View to Generate Table : tblUserAuthList.cshtml
Razor
@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
C#
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 ListItem = _dbConn.Modules.ToList(); //--for single table



                // var ListItem = (from i in _dbConn.UserMaster
                //              select new { i.UserId, i.Password,i.UserLevel,
                //              i.UserGroup, i.Mobile_No,i.ConfPassword,
                //              i.Department,i.DisplayName,i.Email,i.IsActive}).ToList();
                //.Distinct()
                //.OrderBy(i => i.category_name);

                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
                                         //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 = false,
                                             IsCreate = false,
                                             IsDelete = false,
                                             IsEdit = false,
                                             IsReport = false,
                                             IsView = false,
                                         };
                    }

                    //var ListItem = from a in _dbConn.UserAuth.Where(a => a.UserId == id)
                    //               join b in _dbConn.Modules on a.ModuleID equals b.ModuleID
                    //               join c in _dbConn.UserMaster on a.UserId equals c.UserId
                    //               join d in _dbConn.tblDepartment on c.Dept_ID equals d.Dept_ID
                    //               into user_auth
                    //               from d in user_auth.DefaultIfEmpty()
                    //               select new User_Auth
                    //               {
                    //                   UserId = a.UserId,
                    //                   DisplayName = c.DisplayName,
                    //                   Department = d.Department,
                    //                   ModuleID = a.ModuleID,
                    //                   Module_Name = b.Module_Name,
                    //                   GroupID = b.GroupID,
                    //                   IsAccess = a.IsAccess,
                    //                   IsCreate = a.IsCreate,
                    //                   IsDelete = a.IsDelete,
                    //                   IsEdit = a.IsEdit,
                    //                   IsReport = a.IsReport,
                    //                   IsView = a.IsView
                    //               };

                    return PartialView("_TblUser_Auth_List", ModuleList);

                    //return RedirectToAction("User_Auth_List", ModuleList);
                }
                return View("User_Auth_List", null);
            }
            catch (Exception ex)
            {
                return View();
            }
        }

        //public ActionResult Create()
        //{
        //    DDLUserList();
        //    User_Auth ur = new User_Auth();
        //    return PartialView("_User_Auth", ur);
        //}
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(IList<ModuleMaster> collection, string action,string UserID) //---Saving data
        { 
            DDLUserList(); //IFormCollection
            return  View("User_Auth_List", collection);
        }

       private JsonResult DDLUserList() //--Load Dept dropdown list.
        {
            try
            {
                //var LocList1 = _dbConn.PLANT.Select(cc => new { cc.PLANT_CODE, cc.PLANT_NAME }).Distinct();
                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.
Posted
Updated 13-Jun-23 23:12pm
Comments
[no name] 9-Jun-23 9:05am    
Any "building" should be done on the back end. The front end is just a "reflection". Looks like you should be using a "Grid" or a "real" (HTML) table.

1 solution

In your view, ensure that the table is wrapped within a form tag, which will allow you to submit the data to the controller.

Assign a unique name attribute to each table row or input element within the table. This is crucial for binding the data to the model in the controller.

Include a submit button within the form, which the user will click to send the data to the controller.

In the controller, create a corresponding action method to handle the form submission. This method should accept the model that represents the table data.

In the action method, you can access the table data by receiving the model as a parameter. The model binder will automatically bind the posted form values to the model properties.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900