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

Encountering an issue with Firebase Cloud Messaging

I am struggling to implement a push notification trigger whenever a document field is updated. As a newcomer to node.js, I am facing challenges in debugging what seems like a simple function. Below is the code snippet: // Cloud Functions for Firebase SDK ...

Dynamic text input and selection menu with AJAX (PHP and JavaScript)

As a student who is new to Javascript and PHP, I am trying to create a login page for my website that can verify user input in the database using AJAX. For example, when a user enters their username and password, the system should automatically check if t ...

What is the process of transforming a string into an angular binding?

I have a variable called message that contains the text "you are moving to {{output.number}}". I attempted to insert this into a div element using $("#message").html(message); However, it just displayed the entire string without replacing {{output.number ...

What are Fabric.js tools for "Drop Zones"?

Has anyone successfully created a "drop zone" similar to interact.js using fabric.js? I haven't had the chance to experiment with it myself. I have some ideas on how I could potentially implement it, but before diving in, I wanted to see if anyone el ...

Does the Error page in Next JS 13 fail to properly manage fetch API errors?

After referencing the documentation for Next.js with app router, I followed the instructions to create an error.tsx page within my app folder (app/[lang]/error.tsx). This file contains the code provided in the docs. Additionally, I included some API calls ...

Is it possible to load Angular.js without any references?

In the process of reverse engineering a User Interface that is operational but has a few bugs. Created using HTML, CSS, and JavaScript with data acquired through a REST API. The interface is designed for a Windows environment. While examining the index.ht ...

Using Python and Selenium to manipulate the webpage and execute JavaScript can help reconstruct the true HTML structure

I have a very basic Selenium code snippet that I am running: <input name="X" id="unique" value="" type="text"> <script> document.getElementById("unique").value="123"; </script> While I can retrieve the input value "123" using driv ...

Can a condition be incorporated in a gulpfile to execute a task depending on the size of a file?

Currently, I am utilizing gulp for image compression. However, my requirement is to only compress images exceeding 200kb in size. Can JavaScript be used to loop through a directory and selectively run the minification process on files larger than 200kb? ...

The AngularJS uib-typeahead feature seems to be disrupting the interpolation process for the entire page

Encountering an issue with AngularJS 1.50 where interpolation stops working after a specific line of code. <input type="text" class="form-control" id="search" name="search" placeholder="{{ shouldInterpolateButDoesnt }}" typeahead-on-sel ...

Having trouble with the JOSN.parse function not functioning properly

Hello there, I'm currently attempting to extract data from a simple JSON string but encountering an error. The object I am trying to retrieve looks like this: { "heading" : "The movies", "box5" : "Click on icon to add text.", "box1" : "At the movies, ...

The function $(this).addClass() seems to be malfunctioning

While trying to follow a tutorial, I noticed that the style sheet isn't being applied to the clicked element in the list. What could be causing this issue? In the example provided, when a string is added to the text box and the button is clicked, a n ...

Variables defined within a React useEffect are not accessible outside of the function

I'm facing a scope issue where I need to declare a constant variable inside the useEffect hook in React, but the variable is not recognized outside the function. import React, { useEffect } from "react"; function Commentsbox(props) { useEffect(( ...

Issue with HTML Form Data Not Being Reflected in SQL Database

After creating a form to insert values into the database, there seems to be an issue where the database is not being updated despite no errors. Here is the HTML code for the page: <!DOCTYPE html> <html> <title>css</title> <body ...

"Angular File Upload Made Easy with Drag-and-Drop Functionality and Cleverly Positioned

Encountering an issue with Angular File upload in conjunction with relatively positioned elements. The drop target is set to 100% width and height, absolutely positioned. While dragging a file over any non-relatively positioned element, the overlay functio ...

What is the procedure for utilizing Javascript to redirect a user on a website back to the login page if necessary?

Is there a way to redirect a website user back to the login page if they try to access a secure page without logging in first? I'm looking to implement this using JavaScript and cookies. Any suggestions or ideas on how to achieve this seamlessly for t ...

Exploring the applications of the `this` keyword within a jQuery-based JavaScript object

Recently, there has been a challenge in creating a JavaScript object with the specific structure outlined below: function colorDiv(div){ this.div=div; this.div.bind("click",this.changeColor) this.changeColor(){ this.div.css(" ...

I'm having trouble getting the [resetFilterOnHide]="true" functionality to work with primeng 5.2.7. Can anyone provide a solution for this issue?

I'm experiencing an issue with the p-dropdown component where the [resetFilterOnHide]="true" attribute isn't working as expected. When I type in the filter bar, close the dropdown by clicking outside of it, and then reopen it, the entered filter ...

What could be causing my CSS transitions to fail when using jQuery to add classes?

I'm currently working on a website and I'm facing an issue with the transition not functioning as expected. The problem persists even when the 7.css stylesheet is removed and interestingly, the transition works fine when using window:hover. My a ...

Resolving Unrecognized Vue Variable in PhpStorm

I'm encountering an issue with my Vue script in PhpStorm. Despite setting the variable redirect_to, I am getting an Unresolved variable syntax error during debugging. Please refer to the image below for further information. How can I resolve this prob ...

Identify 404 errors in multi-file routes with Express

Recently, I've been diving into using Express and I'm facing some challenges with detecting 404 errors. In my main file app.js, I launch the server and specify different files to handle various requests. For instance: const app = express(); app ...