Repeatedly storing values from a multi-select dropdown

I have successfully implemented a select element that can now save multiple options on the FrontEnd, however the BackEnd functionality is not yet completed.

The challenge lies in modifying the code to loop through and save all selected values, instead of just one at a time.

Unfortunately, I am unsure of how to properly implement this looping mechanism without encountering errors.

Below is a screenshot displaying the selected values along with their respective codes:

Check out the image here

Here's the HTML code for the select element:

<div class="form-group pmd-textfield">
    <label for="TipoPenalAntecedenteCriminal" class="espacamentoLabels">
      Main Criminal Type
    </label>
    <select asp-items="Model.ListTipoPenal"
     name="COD_TIPO_PENAL_PRINCIPAL"
     id="TipoPenalAntecedenteCriminal"
     form="formAntecedenteCriminal"
     class="select-codigo" multiple
     onchange="mostrarOutroDeCombo(this, 'OutroTipoPenalAntecedenteCriminal');">
          <option value="">Select the relation</option>
     </select>
 </div>

This is the snippet of code in the Controller that needs to be modified to handle multiple selections:

This code requires modification to correctly save all specified values.

 [HttpPost]
        public JsonResult SalvarAntecedenteCriminal(IFormCollection form)
        {
            #region GET USER DATA
            var identity = (ClaimsIdentity)User.Identity;
            string usuarioLogado = identity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            #endregion

           ...

            return Json(antecendeteCriminal);
        }

An error occurs while attempting to save the selected values, specifically in the line "COD_TIPO_PENAL_PRINCIPAL = int.Parse(codTipoPenal)," where the issue arises but data is not saved.

See the problematic area in this image

Answer №1

For saving all the values, make sure to use an integer array for COD_TIPO_PENAL_PRINCIPAL.

public int[] COD_TIPO_PENAL_PRINCIPAL { get; set; }

https://i.sstatic.net/4DZOv.gif

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

Access denial encountered when attempting to submit upload in IE8 using JavaScript

When running the submit function on IE8, I am receiving an "access is denied" error (it works fine on Chrome and Firefox for IE versions above 8): var iframe = this._createIframe(id); var form = this._createForm(iframe, params); ... ... ...

Error encountered in the onPostExecute method due to a type mismatch at line 111 in JSON.java, along with a JSONException stating that the input has ended at character 0

Days have passed, and I am still searching for an answer. As a beginner in android development, I am struggling with the error messages org.json.JSONException: End of input at character 0 and org.json.JSON.typeMismatch(JSON.java:111) appearing in my onPost ...

Issue with Bootstrap.js causing mobile menu to not expand when toggled in Rails app

Despite adding the .toggled class, my hamburger menu is not expanding when I click on the mobile menu. I've tried adjusting the order of the required javascript commands, but it doesn't seem to be working as expected. Here are the steps I'v ...

Express API developed with the use of Node.js

In the process of creating a weather application API using Express in Node.js, I have decided not to utilize a database since no data needs to be saved. The application enables users to input a city name, and the weather information is fetched directly fro ...

Discover the key technique to modify the status of a different component in React

I'm working on developing a popup window component. Here is the initial code for the popup component: The component takes in two props, activity (which can be set to true or false) and content (a view component that will be displayed inside the popu ...

Angular Persistent States in Angular version 2 and beyond

Currently, I am in the process of transitioning an Angular 1.5.X application to Angular 4. Within my app, I incorporate Angular Ui-Router Sticky State from https://github.com/ui-router/sticky-states to prevent loss of content within my view when navigating ...

When the user is actively scrolling in the browser, the button will disappear. However, once the scrolling action is completed, the button will gradually fade

Is there a way to hide the button with the id #stats while the user is scrolling, and then have it fade back in once they finish scrolling? It seems like the code below is not working as expected. Any help would be greatly appreciated! <button id="st ...

Creating a PDF from dynamic HTML and transferring it to an AWS S3 bucket without the need to download the PDF

We have created a web application using React JS where we attempted to generate a PDF. Instead of downloading or opening the PDF in a new window, our goal is to directly upload it to an AWS S3 bucket. We have researched and tried various samples but have n ...

Exploring the tree structure and adding it to a JSON object in Python to fetch JSON data

Below is a snippet of json data for reference: { "id": "67362003", "a": { "b": { "3": 2, "43": 30, "c": "jack", "d": "trail" ...

What is the best way to activate a click event within an ng-repeat loop in AngularJS

Is there a way to trigger an event click handler in angular where clicking the button will also trigger the span element? I've tried using the nth-child selector without success. Any suggestions on how to achieve this? I also attempted to use jQuery s ...

Utilize local storage to dynamically update the background color of a div section

Struggling to create a functionality on my website where users can input a color, save it to localStorage, and have a specific div's background set to that color across all pages. The main content div (with the same ID) needs to display this color con ...

Contrasting outcomes when tackling a problem in node.js versus python

After tackling a challenging leetCode problem, I successfully came up with the following solution: Given d dice, each with f faces numbered from 1 to f, determine the number of possible ways (modulo 10^9 + 7) to roll the dice so the sum of the face up nu ...

Utilize Jquery to transform 3 arrays into separate objects distinguished by unique IDs

Recently, I've been experimenting with a very simplistic jquery admin area menu. My goal is to have jQuery create 3 identical menus with different IDs. I was able to accomplish this by creating a function and calling it three times with various variab ...

Obtaining a response in string format using the $.ajax function

var module = (function(){ return{ loadData: function(url, success, error){ $.when($.ajax({ type: 'GET', cache: false, url: url, contentType: 'application ...

How to remove a specific item from an array in MongoDB using JavaScript

So, I've retrieved a nested array from a database query. The query brings back the following data: { _id: new ObjectId("623rf3f22275f399f88bb"), first_name: 'Are', last_name: 'You', email: '<a href="/cdn-cgi/l/email ...

Having trouble retrieving specific data with curl

Trying to retrieve specific data using cURL from the website . The following code is used to fetch all data: <?php $url='http://dummy.restapiexample.com/api/v1/employees'; $my_curl = curl_init(); curl_setopt($my_curl, CURLOPT_URL, $url); curl ...

Ways to verify the successful creation of a child process in NodeJS

I am attempting to use Node JS child_process to open a file as shown below var child_process =require('child_process'); var spawn = child_process.spawn; var exePath='<exe's path>' var filePath='<file path>' v ...

Utilizing the onclick event to call a function with multiple arguments within Template literals

How can I properly write a function with multiple arguments using JavaScript post ES6 template literals when called by an onclick event? Here is my code: function displayImg(imageUrl, gameName, gameSummary, gameYear, cardId) { cardId = cardId.toStrin ...

Utilizing setState within the useEffect hook can lead to the application experiencing

Why does my code result in an endless loop error? This issue is pointing to the line marked with *: function Blog() { const [blog, setBlog] = useState({}); const query = useQuery(); async function fetchBlog(query) { const data = awai ...

Sending an HTTP POST request from Angular 4 to Java SpringMVC results in the issue of POST parameters not

Currently, I am developing a REST API using Java Maven Spring Boot and Spring MVC. I have encountered an issue where Angular POST request parameters are not being recognized by SpringMVC's @RequestParam. Below is the Angular code snippet; saveAsSit ...