Methods for transferring checkbox values from JavaScript/view to controller in MVC

Currently, I am developing a form that allows users to select up to 11 football players from a list using checkboxes. The players are categorized and named by their playing positions.

@if(item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 1).FirstOrDefault()) {
    @Html.CheckBox("goalkeepers", false)
}

@if(item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 2).FirstOrDefault()) {
    @Html.CheckBox("defenders", false)
}

@if(item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 3).FirstOrDefault()) {
    @Html.CheckBox("midfielders", false)
}

@if(item.PlayerPosition.FantasyFootball_PlayerToSeason.Select(x => x.PositionID == 4).FirstOrDefault()) {
    @Html.CheckBox("forwards", false)
}

To display the selected values in a pop-up box when a button is clicked, I have utilized the following JavaScript code snippet:

$('#button').click(function() {
    alert($('input[type="checkbox"]:checked').eq(0).val()); // 1st
    alert($('input[type="checkbox"]:checked').eq(1).val()); // 2nd
    alert($('input[type="checkbox"]:checked').eq(2).val()); // 3rd
    alert($('input[type="checkbox"]:checked').eq(3).val()); // 4th
    alert($('input[type="checkbox"]:checked').eq(4).val()); // 5th
    alert($('input[type="checkbox"]:checked').eq(5).val()); // 6th
    alert($('input[type="checkbox"]:checked').eq(6).val()); // 7th
    alert($('input[type="checkbox"]:checked').eq(7).val()); // 8th
    alert($('input[type="checkbox"]:checked').eq(8).val()); // 9th
    alert($('input[type="checkbox"]:checked').eq(9).val()); // 10th
    alert($('input[type="checkbox"]:checked').eq(10).val()); // 11th
});

My current challenge lies in passing these selected values to the controller so that they can be stored in the database. Since these checkboxes are part of a partial view and not directly related to the model, this task is proving to be complex.

I am open to suggestions on how to efficiently capture the IDs of each selected player for recording purposes. It would be ideal to record each player's ID individually rather than as an array.

In the excerpt below from my controller, I have outlined where I intend to include the selected values in my table (currently commented out):

   [HttpPost]
   [ValidateAntiForgeryToken]
   public ActionResult Create([Bind(Include = "FantasyTeamID,Id,FantasyTeamTypeID,Player1,Player2,Player3,Player4,Player5,Player6,Player7,Player8,Player9,Player10,Player11,FirstEntered,LastUpdated,FormationID,GameweekID")] FantasyFootball_FantasyTeam fantasyfootball_fantasyteam)
    {

      if (ModelState.IsValid)
      {
        db.FantasyFootball_FantasyTeam.Add(fantasyfootball_fantasyteam);
          fantasyfootball_fantasyteam.Id = User.Identity.GetUserId();
          fantasyfootball_fantasyteam.FantasyTeamTypeID = 1;
          //fantasyfootball_fantasyteam.Player1 = 2398;
          //fantasyfootball_fantasyteam.Player2 = 491;
          //fantasyfootball_fantasyteam.Player3 = 850;
          //fantasyfootball_fantasyteam.Player4 = 461;
          //fantasyfootball_fantasyteam.Player5 = 2845;
          //fantasyfootball_fantasyteam.Player6 = 482;
          //fantasyfootball_fantasyteam.Player7 = 1028;
          //fantasyfootball_fantasyteam.Player8 = 2516;
          //fantasyfootball_fantasyteam.Player9 = 2586;
          //fantasyfootball_fantasyteam.Player10 = 2230;
          //fantasyfootball_fantasyteam.Player11 = 2893;
          fantasyfootball_fantasyteam.FirstEntered = DateTime.Now;
          fantasyfootball_fantasyteam.FormationID = 1;
          fantasyfootball_fantasyteam.GameweekID = 47;
          db.SaveChanges();
          return RedirectToAction("Index");
        }

Answer №1

To transfer all checkbox inputs into an array and send them to the controller for processing, loop through each one and save the value in the database.

let transactions = [];
transactions.push($('input[type="checkbox"]:checked').eq(0).val());

Afterwards, transmit the same 'transactions' array to the MVC action.

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

Executing window.open from Html.Actionlink in ASP.NET MVC 4

Here is the code block I am working with: @foreach (System.Data.DataRow drEquipment in Model.EquipmentList.Rows) { <tr> <td valign="top">@drEquipment["ColumnName"]<br /></td> <td valign="to ...

center the view on the specified element

Utilizing ReactJs, I am developing a horizontal timeline that showcases dates. For instance, there is a list of 100 elements, each containing a date and text content. The dates are displayed horizontally using flex-direction="row" and overflowX ...

Using jQuery to Implement Car Turn Signals (Blinkers)

Recently, I've been faced with an unusual challenge. I need to incorporate car turning lights functionality into my website. Specifically, I have to create a scenario where clicking either the left or right button triggers the corresponding green arro ...

Organize state objects with React's sorting capabilities

I'm currently working on implementing a feature where the user can click on the table header ("First Name", "Last Name", etc) and have the data sorted accordingly. <Container> <table className="table table-hover"> ...

Angular: The application has encountered an error due to an undefined property reading issue, resulting in a type error

Here is the code for the company.ts file: company.ts file - List item export class Company{ gstNo:number; contactNumber:number; contactName:string; phoneNo:number; address:string; companyName:string; } import { Injectable } ...

Having trouble displaying options in VueJS Component using datalist

Currently, I am harnessing the power of VueJS and its components to create an extensive array of datalists and selectors, each equipped with a submit button for validation upon form submission. Initially, I successfully implemented a datalist within a com ...

How to locate the duplicate elements within an array using JavaScript

There are two different sets of numbers Numbers1=[ 0, 1, 2, 0, 2 ]; Numbers2=[ 0, 0, 1, 2, 2 ]; The goal is to determine the index of each element in Numbers2 from Numbers1 and create a new array like [0,3,1,2,4]; If you would like to see the code I wr ...

Encountering difficulties during the migration process from a JavaScript to a TypeScript React Component

I've encountered some challenges with configuring TypeScript in my project. Initially, I developed my application using plain JavaScript. However, eager to learn TypeScript, I decided to convert my JavaScript project into a TypeScript one. To achiev ...

Transform a 2-dimensional array into Leaflet.js markers

Hey there, I'm currently facing an issue with generating markers using leaflet js. I have an object that includes multiple entries for each year, and my goal is to create a layer group for each year that can be toggled on and off. However, I've e ...

Discover the color value within an array that begins with the "#" symbol

In my PHP code, I have written a function that extracts values from a CSS file and creates an array. Now, I need to loop through this array and create another array that only contains color values (strings starting with #). The challenge is that the length ...

Assigning a value to a variable can prevent the occurrence of an

My recursive code consists of two pieces aiming to print out half of the array recursively until we reach arrays of length 1. Surprisingly, the code without variable assignment runs infinitely, while the code with variable assignment behaves as expected. ...

Is it possible to capture a screen recording in Selenium using JavaScript?

While my tests are running, I am looking for a way to record my screen. I came across a post about screen recording using Java at . However, the code provided is in Java and I require something in JavaScript. Is it possible to record the screen using Jav ...

Issue with NPM Scripts Post Hook Triggering

Currently, I am exploring the use of npm scripts to gradually phase out my dependency on Gulp. To begin, I have created a single custom script called watch. This script will eventually execute all other scripts prefixed with the name watch, such as watch:s ...

Preventing routevalues from being nulled in Asp.Net Core MVC Html.ActionLink

Struggling with the transition from an Asp.Net MVC 5 project to an Asp Net Core MVC app. The @Html.ActionLink helper isn't behaving as expected during porting. In one of my views, I'm using @Html.ActionLink("Back to " + @action, @action, "Some ...

Issue with Google Maps iFrame not loading when utilizing JavaScript variables in the "src" attribute

Currently, I am facing an issue with utilizing JavaScript variables containing GPS latitude and longitude values in the "src" attribute of an iFrame in an HTML file for displaying image EXIF data on a Google Maps iFrame. When I hardcode specific latitude ...

Can anyone offer a straightforward method for obtaining JavaScript output in Java within the Eclipse environment?

Currently, I am attempting to retrieve the return value from a JavaScript function that I have created. Although I can achieve this using a complex method involving listeners, I am interested in utilizing Eclipse's Browser.evaluate method. For practi ...

Unable to retrieve the API key in Nuxt framework

I am fairly new to NuxtJS and have been following tutorials on it. I am having trouble displaying the {{planet.title}} on my page. However, when I use {{$data}}, I can see all the planets. I want the title of the planet's name that I have in the slug ...

Is it possible to rotate the caret in the dropdown 180 degrees using only CSS?

Is there a way to achieve a 180° rotation of the caret in a dropdown menu upon clicking it, creating the illusion of an animation? I would prefer to accomplish this using CSS only, without the need for JavaScript, but I am open to any suggestions. .se ...

React - Error: you have a syntax problem because there is an unexpected token <

I am working on a project using Express, pg, and react. However, I have encountered some issues with React. Here is the directory of my project index.js var express = require('express'); var server = express(); var path = require('path&ap ...

Is there a way to send my form via the submission button inside a modal in ASP.NET MVC?

Although it may seem like a simple question to some, I am struggling with understanding how to implement a submit button that opens a modal and displays user input from a text box. The user can then choose to edit their input or proceed with submitting it. ...