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

Creating dynamic VueFire references is a powerful feature that allows for more flexibility and customization

I am currently exploring the creation of refs dynamically: The initial ref I created works fine as it is hardcoded, but the second one does not seem to work because it is dynamic: firebase: function(){ return { categories: db.ref('categ ...

Since switching to PHP 5.5 from version 3.x, I have noticed that it is attempting to interpret my JavaScript comment within a script tag in a PHP include file

After a long break from working with PHP, I recently encountered an issue with an older website I built using PHP and the include function. The site was functioning perfectly until the web host updated PHP to version 5.5, causing a strange bug where it see ...

Continuously transmitting PNG files to a server. I intend to instruct the receiving browser to automatically refresh at set intervals

I have a continuous task where my code is uploading a png to an http server every few seconds. I am looking for a way to implement some kind of marker that will trigger the browser to automatically refresh every 500ms, either through browser-side javascrip ...

Modify the array dynamically within the Factory

I am currently working on a simple app where I want to display embed videos with the click of a button. It was quite challenging for me to dynamically bind my embed players, but I managed to do it successfully. I created a factory that contains my data in ...

Ways to apply CSS to a changing div ID

I am looking to apply CSS to a dynamically generated div ID. var status = var status = item.down().next().innerHtml(); if(status == "test") { var c = 'item_'+i ; c.style.backgroundColor = 'rgb(255, 125, 115)'; //'ite ...

Navigating to a different directory using Node.js and ExpressJS route mapping

I'm struggling with setting up routing using ui.router. This is the structure of my folders: https://i.stack.imgur.com/Fu0A9.png In the app.js file within the javascripts folder, I have the following code: var app = angular.module('testing&ap ...

React - The content of my JSON.String vanishes upon being placed inside a div element

My NFTDetails component includes a description from a JSON, which contains \n\n in it. Strangely, there are no new lines when I render the JSON value in a div, but when I log it to the console in Firefox, new lines appear. How can I make use of ...

Transform the selected component in Material-UI from being a function to a class

Hello, I am currently learning about React and I have started using the select button from material-ui. The code I found on the material ui page is for a functional component, but I am more comfortable with class components. Here is the code snippet provid ...

How can I dynamically change the default value of the selected option dropdown in React-Select when a new option is chosen?

Can you help me understand how to update the default displayed value on a dropdown in a react-select component? When I choose a different option from one dropdown, the select dropdown value does not change. I've attempted this.defaultValue = option.va ...

Unable to execute internal functional tests due to this error: [POST http://localhost:4444/wd/hub/session] unable to connect - ECONNREFUSED

Currently working with node 0.12 and intern 3 in order to execute functional tests, but encountering the following error: SUITE ERROR Error: [POST http://localhost:4444/wd/hub/session] connect ECONNREFUSED at Server.createSession <node_m ...

Is it viable to create an onClick event for the text content within a text area?

I'm working on a project that involves displaying XML data in a textarea and creating an onClick event for the content within the textarea. For example: <textarea>Hello Web, This is a simple HTML page.</textarea> My goal here is to create an ...

How to Ensure an Element Appears Above Another Despite Z-Index Troubles?

After conducting approximately 2 hours of research on this topic, I was unable to find clear answers or solutions. Hence, I have decided to address the issue here. The problem I'm facing is as follows: Due to the nature of HTML/CSS, it seems impossi ...

"Exploring the Synchronization Feature in Vue.js 2.3 with Element UI Dialog Components

Recently, I've encountered some changes while using Element UI with the latest release of Vue.js 2.3 In my project, a dialog should only be displayed if certain conditions are met: private.userCanManageUsers && private.pendingUsers.length > ...

What is the best way to handle errors generated by my jsdom.jqueryify callback function?

When running this code in node.js, the output is a stack trace of an error that occurs on line 9. Surprisingly, the error on line 7 seems to be 'absorbed' by Node. Even when wrapped in a try/catch statement, the detailed stack trace output is not ...

Guide to automatically loading a default child route in Angular 1.5 using ui-router

Hello, I am looking to set a default child route to load as soon as the page loads. Below is the code snippet: $stateProvider.state('userlist', { url: '/users', component: 'users', data:{"name":"abhi"}, resolv ...

"Emphasize menu items with an underline as you navigate through the

I am using Gatsby with React and have a navigation menu with links. I would like to make it so that when a link is clicked, a border bottom appears to indicate the current page, rather than only on hover. <ul className="men" id="menu"> ...

Hide the burger menu when a link is clicked

Is there a way to make my Bootstrap burger menu automatically close when the user clicks on a menu link, rather than having to click on the burger itself? I've tried using some JavaScript code but it ends up disabling the burger menu entirely. Can any ...

using document references in puppeteer's evaluate/waitFor function

I'm feeling a bit lost when it comes to understanding the document reference in puppeteer's evaluate method. The official documentation shows some code that includes this reference within a waitFor function in a node script. I get that these line ...

"Incorporating Node.js (crypto) to create a 32-byte SHA256 hash can prevent the occurrence of a bad key size error triggered by tweetnacl.js. Learn how to efficiently

Utilizing the crypto module within node.js, I am creating a SHA256 hash as shown below: const key = crypto.createHmac('sha256', data).digest('hex'); However, when passing this key to tweetnacl's secretbox, an error of bad key siz ...

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...