Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED.

Following your suggestions, I implemented the function as shown below:

  [HttpPost]
  public ActionResult populate_place(string lati, string longi)
   {
  list_placesModels list_place = new list_placesModels();
  list_place.Latitude = lati;
  list_place.Longitude = longi;
  return View();
   }   

However, after implementing this function, the new view is not displaying and it still shows the old view. The redirection to the new view is not happening for some reason.

////////////

I have integrated Google Maps geocoding feature into my Razor view in an ASP.NET MVC application to retrieve latitude and longitude data from locations. I want to pass this data to a controller function but nothing seems to be working. Below is a snippet of my code:

JavaScript code:

if (status == google.maps.GeocoderStatus.OK) {

  map.setCenter(results[0].geometry.location);
  var marker = new google.maps.Marker( {
    map: map,
    [0].geometry.location
  });

  // Trying to pass latitude and longitude values to list_places() function in UserController.
  latitude = results[0].geometry.location.lat();
  longitude = results[0].geometry.location.lng();   

  $.post("/User/list_places",
    {
      lati: latitude,
      longi : longitude
     });

Controller:

public ActionResult list_places(string usernameid, string lati, string longi) {

  list_placesModels list_place = new list_placesModels();
  list_place.Latitude = lati;
  list_place.Longitude = longi;
  return View(list_place);
}

Answer №1

Looks like there are a few missing elements in your code. First, make sure to include the [HttpPost] attribute on the action you are posting to. Also, ensure that the correct number of arguments is being passed; it appears you are passing 2 arguments but expecting 3. See the example below for clarification.

Html/Javascript

<script type="text/javascript>
function buttonclick() {
    var requestData = {
        lati: 'latitude',
        longi: 'longitude'
    };

    $.ajax({
        url: '/Home/populate_place',
        type: 'POST',
        data: requestData,
        dataType: 'json'
    });
};
</script>

<button onclick="buttonclick()">Click</button>

Controller Action

[HttpPost]
public ActionResult populate_place(string lati, string longi)
{
    return RedirectToAction("About", "Home");
}

If you set a breakpoint on the controller actions return statement, and inspect the parameters, you'll see that they are populated correctly.

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

Tips for streamlining distinct states and generalized state in UI Router

I've set up the following configuration in my JS app under the $stateProvider section using angular ui-router: .state('login', { url: '/login', templateUrl: 'app/login/login.tmpl.html', controller: &apo ...

Error in the delete function on a JSF webpage

I am currently working on implementing a JSF table with a delete button. Below is the JavaScript code that triggers the dialog box: function showDialog(a){ $("<div />", { text: a }).dialog({ width: 600, ...

Combine large arrays

Hey, I'm encountering some issues while trying to merge large arrays in a React Native app. Specifically, I am attempting to implement infinite scroll on React Native. The issue arises when the array reaches 500+ items; every time I add more items, my ...

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

Steps to effectively pass parameters in a function object literal

As a JavaScript beginner utilizing an object literal pattern, I am attempting to pass integers as min and max parameters to a function in order to retrieve a random number for use in another function called "interaction". However, I encountered the error m ...

The jQuery ajax function is not properly displaying or hiding the loader div

While attempting to call PHP code using a jQuery AJAX function, I encountered an issue where I wanted to display a loader div while the request was being sent and then hide the div once the request was complete. To simulate this scenario, I deliberately de ...

The error message "AWS Lambda Node 18: fetch is not defined, please resolve or include global fetch" indicates that

Seeking assistance with calling the Pagespeed Insights API from an AWS Lambda using Node 18. Struggling to make fetch() function properly. Cloudwatch logs indicate the message "inside the try about to fetch," but then nothing else appears. The Lambda con ...

Dealing with multiple v-on:click events in Vue.js

Can I add multiple v-on:click events to the same element? I want to toggle a navigation menu and trigger a CSS animation on the element that toggles the navigation. <template> <div> <nav v-if="visible"> <ul&g ...

Solving required packages in Express server

I am encountering difficulties with resolving dependencies on my express server. Below is the structure of my project: Calculator --dist ----app -------calculator.js -------server.js --node_modules --src ----app --------calculator.js --------server.js -- ...

Keeping JSP current with changes made to files on the client side

Currently, I am tackling a project that consists of two main components: a) A Java Application that runs on a client machine. b) A Web Application that is hosted on a web server. The Java Application generates results at random intervals. These results n ...

In React Router, redirect when location.state is not defined

import React, { useState } from "react"; import { Redirect } from "react-router-dom"; function Update(data) { if(!data.location.state) return <Redirect to="/"/> const [name, setName] = useState(dat ...

Getting Rid of Angular Material Suggestions: A Step-by-Step Guide

<md-autocomplete ng-model="ctrl.searchText" md-selected-item="ctrl.selectedItem" md-selected-item-change="ctrl.selectedItemChange(item)" md-search-text="ctrl.searchText" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" ...

How to properly handle Angular routing errors and best practices?

Currently, I have been delving into learning Angular to integrate with my Ruby on Rails application. However, I have encountered some challenges specifically related to routing. Here is a snippet from my app.routing file: import { NgModule } from '@ ...

My website code being stored in cache by Chrome (as well as other browsers)

Issue: I am facing an issue with hosting a widget on my client's website where the widget needs to be different for each page. To display the widget, the client embeds a script tag on their pages. This script is loaded on every page and the content ...

Adjusting the quantity of buttons in real-time following an ajax request

Creating buttons dynamically in an Ajax success function can be a challenge when the number of buttons varies each time. I am able to create the buttons, but since the exact number is unknown, adding the correct number of button listeners becomes tricky. ...

Lost Vuex struggles when it is manually navigating a route in Vue-router

Exclusively on Safari browser, I encounter an issue when manually entering the URL in the navigation bar after logging in. For example, if I type "http://x.x.x.x:8080/gestione", the browser loses the vuex store state (specifically the gest_user module with ...

Encountering issues with extension CLI - "Unable to utilize the import statement outside a module"

Recently, I've been attempting to integrate the Afinn-165 node package (https://www.npmjs.com/package/afinn-165) into my Google Chrome extension. The goal is to analyze the sentiment of text scraped from each page. Being a novice in web development, I ...

I am searching for a straightforward Rails sample that incorporates Ajax

Currently, I am on a quest to find a solid demonstration of how AJAX and JSON interact with Rails. I have a Rails application that relies on standard forms and I am looking to enhance it with some ajax functionality. Unfortunately, I haven't come acro ...

Form an array using the values that are returned

As I iterate through an object and extract elements, my console.log displays: ["item 1"] ["item 2"] ["item 3"] and so on. All I want is to create a new array formatted like this: ["item 1","item 2","item 3"]; ...