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"/>
}