How can I effectively send data from a view to a controller using AJAX in C# using Leaflet?

Every time I attempt to pass data from the view to the controller, I keep receiving an "alert request failed" message.

I am uncertain of the datatype for leafletLats and leafletLngs, but they are both arrays derived from coord which is of type LatLng[].

Could someone help me identify what may be causing the Post method to not go through? Is there an issue in the controller?

In the View:

routeControl.on('routeselected', function (e) {
            var coord = e.route.coordinates;
            var name = e.route.name;
            var leafletLats = coord.map(function(point) {
                return [point.lat];
            });
            var leafletLngs = coord.map(function(point) {
                return [point.lng];
            });

            alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLats);
            alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLngs);

            $.ajax({ 
                type: 'Post',
                url: '/Map/GetRouteCoordinates',
                data: JSON.stringify(leafletLats),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) { 
                    alert(`Request passed!`);
                    console.log(data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(`Request failed!`);
                }
            });

In the controller:

[HttpPost]
public ActionResult GetRouteCoordinates(MyModel test)
{
    //do something with the result
    Debug.WriteLine("data passed back");

    return View();
}


public class MyModel
{
    public List<MyModel_Value> latList { get; set; }
}

public class MyModel_Value
{
    public double lat { get; set; }        
}

Answer №1

I made adjustments and updated the information to

data: JSON.stringify({ arr: stringifiedArr })
and it successfully resolved my issue.

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

Uncovering the secrets of locating and deleting arrays with the power of jQuery

Is there a way to extract data from an array list and then have it automatically removed once displayed? let fruits = ["Banana", "Orange", "Watermelon"]; For instance, if I want to select the Watermelon element from the array. After retrieving and display ...

Initiate the lengthy operation and proceed with additional duties

public class ExecuteMainTasks() { Task1(); Task2(); ExecuteTimeConsumingTaskOnAnotherThread(); Task3(); Task4(); } In order to ensure that ExecuteTimeConsumingTaskOnAnotherThread() runs on a separate thread and allows Task3 & Task4 ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

Incorporating Chartist.JS with Jade-syntax pages

Hello everyone, I need some assistance with integrating Chartist.JS into a node Template to display a basic bar graph. The script doesn't seem to be working properly and I'm unsure of what's causing the issue. Can anyone please take a look a ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...

What is the best method for uploading an image to the server side using JQuery AJAX and without any additional libraries in an ASP.NET web form

Hey there, I recently discovered a code that allows me to drag and drop an image into a designated zone for display, and it works like a charm. However, despite numerous attempts, I have been unsuccessful in uploading the file. I understand that the path ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

Animation will cease once the page is refreshed via Ajax

I'm facing a challenge with a problem that I can't seem to resolve. The issue lies in my use of this plugin for displaying random images. The only step left is to refresh the content within the div. However, every time I attempt to do so, the an ...

Having trouble creating a text channel in discord.js

Today I successfully programmed a bot to respond to the "!new" command, but encountered an unexpected issue. The current functionality of the bot creates a channel named "support-1" when prompted with the "!new" command. However, every subsequent use of th ...

Display open time slots in increments of 15 minutes on Fullcalendar

Currently, I am utilizing the fullcalendar plugin with the 'agendaweek' view. My goal is to showcase the available time slots as clickable and highlight the busy ones with a red background. Handling the highlighting of busy slots is not an issue ...

What is the process for retrieving an HTML file dynamically and using it to populate a DIV with jQuery?

Can you explain how to carry out the following three steps: 1. Retrieve an HTML source from the server side 2. Utilize the retrieved source to generate a DIV element 3. Add the generated DIV element to the <body> element ...

What is the best way to create an image carousel that continuously loops instead of resetting?

Currently tackling an issue with my image carousel project. The automatic function of the slider is not functioning as desired. Instead of looping back to the first image when it reaches the last one, it moves all the way back to the beginning, displaying ...

AngularJS $http.get request not working as expected

Hi there, I'm currently facing an issue with retrieving data from a webpage for use on my own website. I'm working with AngularJS and attempting to fetch data from . When checking my page in Chrome, I encountered the following error: Refere ...

Is there a way to automatically remove files from the "dist" directory when deleting the prototype from the "src" folder?

I am new to build systems and seeking assistance with the following question. Here is the structure of my boilerplate: /src (working folder) ___/templates(jade files) ___/scss ___/scripts /dist (compiled files) ___/css ___/js ___.html files In the te ...

Make sure to validate a form when submitting from an external source rather than through an HTML

In my form, there are various input fields (some acting as inputs even if they're not). Each field is validated upon submission by angular validation and html attributes like required, ng-maxlength, minlength, etc. Now, we want to implement a keyboar ...

Obtain $stateParams excluding UI-navigation

Is there a way to access $stateParams without using a <ui-view> tag in the HTML? I'm trying to make this code function properly: .config([ '$locationProvider', '$stateProvider', function($locationProvider, $stateProvide ...

Passing the AngularJS ng-model from a template to a directive's controller

I have created a directive with a controller that is responsible for building a form to post comments to an API through CommentsService Here is a snippet of how my directive looks: app.directive('appComments', function( CommentService ) { r ...

The sendFile function fails to transmit any data

Currently working on integrating the mailChimp API into my project, but facing an issue with the resFile code that handles sending the success response. The current code snippet: async function run(){ try { const res = await mailch ...

The code functions properly when tested on a local server, but doesn't produce any results when

Currently, I am working on customizing a premade website and have been tasked with making a modification. The goal is to implement a confirmation box that appears when a button to delete a meeting task is clicked, rather than immediately deleting it. Afte ...