Retrieve the Checked Value of a Checkbox Using Ajax Post in MVC

Can anyone provide assistance?

This is the code I am working with:

Index.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>jQuery With Example</title>
    @Scripts.Render("~/bundles/jquery")
    <script type="text/javascript">
        $(function () {

            $('.chkview').change(function () {
                $(this).closest('tr').find('.chkitem').prop('checked', this.checked);
            });

            $(".chkitem").change(function () {
                var $tr = $(this).closest('tr'), $items = $tr.find('.chkitem');
                $tr.find('.chkview').prop('checked', $items.filter(':checked').length == $items.length);
            });
        });

        function Save() {
            $.ajax({
                url: @Url.Action("Index", "Home" , "Index"),
                type: "POST",
                data: formData ,
                dataType: "json",
                success: function(data){
                    alert(data.RoleID)
                },
                error: function(e){
                    debugger;
                }
        }

</script>
</head>
<body>
    <h2>Access Control-Home</h2>

    <br />
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { RoleID="RoleID" }))
{
    <input type="hidden" name="RoleID" value="1" id="RoleID" />
    <table id="mytable">
        <tr>
            <td>View</td>
            <td>Insert</td>
            <td>Update</td>
            <td>Delete</td>
        </tr>
        <tr>
            <td>Administrator</td>
            <td>
                <input type="checkbox" class="chkview chkview-1" />
            </td>
            <td>
                <input type="checkbox" class="chkitem chkitem-1" />
            </td>
            <td>
                <input type="checkbox" class="chkitem chkitem-1" />
            </td>
            <td>
                <input type="checkbox" class="chkitem chkitem-1" />
            </td>
        </tr>
        <tr>
            <td>Free User</td>
            <td>
                <input type="checkbox" class="chkview chkview-2" />
            </td>
            <td>
                <input type="checkbox" class="chkitem chkitem-2" />
            </td>
            <td>
                <input type="checkbox" class="chkitem chkitem-2" />
            </td>
            <td>
                <input type="checkbox" class="chkitem chkitem-2" />
            </td>
        </tr>
    </table>
    <br />

        <button type="submit" class="buttons buttons-style-1" onclick="Save()">Save</button>
}

</body>
</html>

HomeController.cs

[HttpPost]
public ActionResult Index(string RoleID)
{
   var _roleID = RoleID;
   return View();
}

I have two questions:

  1. How can I parse the values of checked checkboxes using ajax? I want to parse the class names of the checkboxes that are checked. For example, if I check the row 'Administrator', I need an array list like {'chkinsert-1','chkupdate-2'}

  2. How can I get a collection of array values in the controller post method? Example: public ActionResult Index(string RoleID, array[] collChecbox) contents of collChecbox = { 'chkinsert-1','chkupdate-2'} in accordance with the user checked checkboxes input.

Can someone offer assistance please?

Answer №1

Have you considered using Ajax.BeginForm() to easily send form values?

It's important to create a proper model structure first.

MODEL

    public class UserRole
    {
        public Administrator Administrator { get; set; }
        public FreeUser FreeUser { get; set; }
    }
    public class Administrator
    {
        public int Checkbox1 { get; set; }
    }
    public class FreeUser
    {
        public int Checkbox1 { get; set; }
    }

In your View:

    @model Model.UserRole
    <div id="result"></div>
    @using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "result" }))
    {
        <input type="hidden" name="RoleID" value="1" id="RoleID" />
        <table id="mytable">
            <tr>
                <td>View</td>
                <td>Insert</td>
                <td>Update</td>
                <td>Delete</td>
            </tr>
            <tr>
                <td>Administrator</td>
                <td>
                    @Html.CheckBoxFor(m => m.Administrator.Checkbox1)
                </td>
            </tr>
            <tr>
                <td>Free User</td>
                <td>
                    @Html.CheckBoxFor(m => m.FreeUser.Checkbox1)
                </td>
            </tr>
        </table>
        <br />
        <button type="submit" class="buttons buttons-style-1" onclick="Save()">Save</button>
    }

Controller action

    [HttpPost]
    public ActionResult Index(UserRole model)
    {
        return View();
    }

Don't forget to include the ajax library:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generating a three-level unordered list using arrays and for-loops in JavaScript/JSON

Are there more efficient ways to achieve the desired results from this JSON data? Can someone assist me in understanding why it is working and if it can be optimized for cleanliness? <div id="accordion" class="display-data"> ...

Retrieve the Object from the array if the input value is found within a nested Array of objects

Below is the nested array of objects I am currently working with: let arrayOfElements = [ { "username": "a", "attributes": { roles:["Tenant-Hyd"], groups:["InspectorIP", "InspectorFT"] } }, { ...

How to solve the issue of synchronizing data fetching from a json-server and displaying it in the UI with React?

While working with json-server to retrieve data and display it in the UI, I often face a recurring issue that leaves me puzzled. The process of fetching data is asynchronous, which means that setting the state after fetching the data takes some time. As a ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...

Is there a way to trigger an AJAX request right before I leave the page or unload it?

When the window is about to be unloaded, an AJAX request is sent to a specific URL including the recent tracking ID and the time spent on the page in seconds. However, the behavior I am experiencing is an alert displaying [object Object]. ...

Angular is showing an error indicating that the property "name" is not found on an empty object

After thorough checking, I have confirmed that the property does exist with the correct key. However, it is returning an error message stating name is not a property of {}. I attempted to assign this object to an interface along with its properties but enc ...

Is there a method to incorporate a scroll event into the ng-multi-selectdropdown, a npm package?

Query: I need to incorporate a scroll event in the given html code that triggers when the div is scrolled. However, I am facing issues with implementing a scroll event that works when the elements are being scrolled. <ng-mult ...

Activate Bootstrap datetimepicker by using the enter key to automatically populate the initial date

Check out the Bootstrap datetimepicker on this page: I'm trying to make it so that when the datetimepicker is first shown, pressing the enter key will hide the widget and insert the current date into the input field. I've experimented with a few ...

Adding a line break ( ) in a paragraph within a TypeScript file and then transferring it to HTML does not seem to be functioning properly

Angular Website Component: HTML file <content-section [text]="data"></content-section> TypeScript file data = `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's stand ...

Strange behavior is observed when using ng-view inside ng-controller, especially when refreshing the

Here is the code I am working with: <body ng-controller="CoreCtrl"> <div ng-cloak> <!-- NavBar --> <div ng-include="'/app/core/navbar.html'"></div> <!-- Main content --> <div class="con ...

The ajax response is currently inactive

I have been working on a web application that was functioning perfectly until I tried to integrate ajax. After adding ajax, the same first page keeps loading repeatedly without any new content or error messages. Can anyone please help me understand why my ...

Integrating React js with Layout.cshtml: Mastering the Fusion of React Routing and ASP.NET MVC Routing

My current project involves an ASP.NET MVC core application with the View written in cshtml. The routing follows the conventional asp.net mvc routing pattern. However, I've recently implemented a new module using React JS. Now, I'm faced with the ...

The component contains a render method, however, it does not inherit from React.Component

A component is displaying a render method, however it does not extend React.Component. This may lead to potential errors. Please modify <Test> to extend React.Component instead. When utilizing the extends-classes library, it results in a react compo ...

Enable users to choose either today's date or a future date by implementing AngularJS UI Bootstrap

I am currently utilizing the ui-bootstrap directive for a datepicker. My goal is to restrict the selection of dates to today's date or any future dates. Below is the HTML code snippet for the datepicker: <div class="input-group"> ...

Encountering an issue while trying to set up fs-ext with npm: error C3861: the 'fcntl' identifier cannot be

I encountered an error while trying to install fs-ext on my Windows 10 64-bit machine with Node.js v8.1.3 and npm v5.4.0. Any recommendations on how I can successfully complete the installation? PS C:\users\desktop\auth> npm install fs-e ...

The issue of jQuery not functioning properly within a Rails environment

Despite my efforts, I am still struggling to make jquery work in rails. I have installed the 'jquery-rails' gem and added the require statements in the application.js file. Below is a sample test page that I have been testing: <!DOCTYPE htm ...

What steps can be taken to stop 'type-hacking'?

Imagine owning a popular social media platform and wanting to integrate an iframe for user signups through third-party sites, similar to Facebook's 'like this' iframes. However, you are concerned about the security risks associated with ifra ...

Guide to implementing a JQuery datepicker in a basic Rails application

Being a beginner in Ruby On Rails and web programming, I am transitioning from a traditional desktop programming background. While I have created a few simple rails applications before, this is my first attempt at using Rails3 and integrating jQuery. I am ...

Do not proceed if the process has encountered a failure

Using PHP code, I have created a way for people to get in touch with me and share their opinions. Here is the PHP code snippet: <?php $to = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef9b868c848a9bc19d869b8e988a8 ...

Obtain the response body in Nest JS middleware

Currently, I am working on developing logging middleware for my project. My main goal is to log the response body specifically in 500 responses. However, I have encountered an issue where the response body is not present in the Response object when using a ...