How can I send checkboxes generated by JavaScript to the controller for saving in a table?

I have a scenario where checkboxes are generated dynamically based on Google Maps search results. I am looking to pass these checkboxes to the controller in order to store them in a database and retrieve them later.

Currently, I have a View where users can search for a city. The input is sent back to the controller which then renders a new view to display nearby locations on a Google map. These nearby locations are added dynamically as checkboxes within a <div> element using JavaScript.

I have attempted to pass the checkboxes as both a string array and an array of my model class. However, I am only able to receive the results in the controller using string[], but encounter issues when trying to save them to the database.

    [HttpPost]
    public IActionResult Itinerary(string[] destination)
    {
        foreach (var item in destination)
        {
            _context.Itinerary.Add(item);  // error: 'Argument 1: Cannot convert from 'string' to NameSpace.Model.Itinerary"
        }

        _context.SaveChanges();
        return View();
    }

Javascript check boxes

function createMarkers(places) {
    var bounds = new google.maps.LatLngBounds();
    var placesList = document.getElementById('places');
    for (var i = 0, place; place = places[i]; i++) {
        var image = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
        };
        var marker = new google.maps.Marker({
            map: map,
            icon: image,
            title: place.name,
            animation: google.maps.Animation.DROP,
            position: place.geometry.location
        });

        var checkbox = document.createElement('input');
        checkbox.type = "checkbox";
        checkbox.name = "destination";
        checkbox.value = place.name;
        checkbox.id = "id";
        checkbox.setAttribute("asp-for","LocationName");

        var label = document.createElement('label')
        label.htmlFor = "id";
        label.appendChild(document.createTextNode(place.name));

        placesList.appendChild(label);
        placesList.appendChild(checkbox);

Form Posting checked boxes back to controller

@using (Html.BeginForm("Itinerary", "Itinerary", FormMethod.Post))
{ 
        <div multiple id="places" > </div>
        <button id="more">More results</button>

    <input type="submit" value="Finished"/>
}

Answer №1

Upon further investigation, the issue lies within this specific line:

 _context.Itinerary.Add(item);  // problem: 'Argument 1: Cannot convert from 'string' to NameSpace.Model.Itinerary"

To resolve this, you must instantiate an Itinerary:

 _context.Itinerary.Add(new Itinerary { Destination = item });

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

JavaScript - Add up and combine an unspecified number of arrays in one concise statement

Have you ever come across the answer to the question about the Javascript version of Python's zip function? It demonstrates a clever method for merging any number of arrays into a single array through a concise statement. zip= rows=>rows[0].map((_ ...

Is there a more concise method to reference the parent scope in AngularJS in this scenario?

Is there a shorter way to reference the parent scope within this controller? $scope.tables = []; $scope.newTable = function(){ $scope.tables.push({name:"Table " + ($scope.tables.length+1),cols:[]}); $scope.selected = $scope.tables.length-1; }; I ...

Unable to display images - PhoneGap

I am experiencing an issue where images that are being dynamically added to my HTML display correctly in Firefox, but on all the Android devices I have tested, the images do not appear. Instead, a box with their alt text is shown. HTML: <div class="ui ...

Top method for documenting the subsequent information

I am in the process of setting up a SQL Server database to log vehicle movements, cleaning, repairs, and more. One challenge I am facing is how to effectively store the following information: I need to keep track of each instance when a vehicle undergoes ...

Troubleshooting problem in Vercel with Next.js 13 application - encountering "Module not found" error

Encountering a deployment issue with my Next.js 13 application on Vercel. I recently implemented the Parallel Routes feature of Next in my codebase. While pushing the changes to create a new pull request on GitHub, the branch's deployment on Vercel is ...

Troubleshooting 404 errors with Cordova, AngularJS, and Node.js (Express) when using $http with

I'm currently testing in an Android environment using Cordova, AngularJS, and Node.js (Express). I'm attempting to retrieve some data using $http(), but consistently encountering a 404 error message (as seen in the alert below). Here's the ...

JS: Implementing a multiple file upload input with JavaScript using an array as the value

I am working with an array of files in JavaScript: var images = []; How can I dynamically create a valid input element to send to the server using AJAX, like this: <input type="file" multiple="multiple" value="{my images array}"> The challenge is ...

NodeJs: Dealing with package vulnerabilities stemming from dependent npm packages - Tips for resolving the issue

Is there a way to address npm vulnerabilities that are dependent on another package? For instance, I'm encountering an error where the undici package relies on the prismix package. Things I have attempted: Executed npm audit fix Ensured Prismix is u ...

Polygon drawing not displaying on openlayers map

My task is to draw a polygon on an OpenLayers map. The code I am using for this purpose is as follows: draw = new Draw({ source: this.vectorSource, type: 'Polygon' }) draw.on('drawend', e => { ...

The element.find() function in Angular struggles to locate input elements nested within other elements

I have been working on a directive that has the following template (simplified): <table> <tr> <td> <input type="text"/> </td> <td> <inpu ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...

Finding the character column type of a MySQL database using the Code First Model in C# Entity Framework

After successfully performing the customary Hello World program, I decided to delve into creating an Entity Framework Code First model which was new territory for me as I had only written C# programs before. The model I created looked like this: class Pre ...

Abstraction of middleware functions

After reviewing my middleware Express functions, I realized that there is repeated code. The first function is as follows: const isAdmin = async (req, res, next) => { try { const requestingUser = await knex('users') ...

MetaMask RPC error encountered: execution failed with code -32000 and message stating "execution reverted"

While working on a DApp project that involves using React and Solidity with an ERC20 contract, I have successfully deployed my smart contract on Rinkeby. I am able to interact with the contract using name() and symbol(). However, I encountered an issue whe ...

What is the best method to update numerous low-resolution image sources with higher resolution images once they have finished loading?

I'm currently developing a website that implements a strategy of loading low-resolution images first, and then swapping them for high-resolution versions once they are fully loaded. By doing this, we aim to speed up the initial loading time by display ...

The ODBC connection to SAP HANA database has suddenly ceased to function

An issue arose when attempting to connect to the SAP HANA database through an ODBC connection in a C# program using the .NET Framework 4.7, with also testing done at .NET Framework 4.0. Error: System.Data.Odbc.OdbcException ERROR [08S01] [SAP AG][LIBODB ...

Background image of HTML Iframe element does not display - Inline style block

https://i.stack.imgur.com/JW26M.png After setting the iframe's innerHTML using this line of code: iframedoc.body.innerHTML = tinyMCE.activeEditor.getContent(); The styles for the elements within the iframe are contained in an inline style block. Ho ...

The reverse proxy is displaying a 404 error message when attempting to access the services

One of our projects involves an Asp.net MVC 4 Application with WCF services. This project is hosted on our iis Production Server P125 (IP: 10.10.10.125), alongside a few other sites. Our Web/Front End Server serves as a Reverse proxy for the production ser ...

Storing repeated inputs in local storage multiple times

I am working on a feature where I need to store data in local storage multiple times using a dropdown menu and some input fields. Currently, I am able to retrieve all the values from the input fields and see them in the console log. My goal is to save thes ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...