You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.Net MVC中批量传递经纬度列表至控制器问题求助

Fixing Duplicate Controller Submissions & Batch Lat/Lng Upload in ASP.NET MVC

Hey there! Let's break down your problem first. The repeated submissions to your controller are almost certainly happening because you're sending a request every time you get a single lat/lng result from the Google Geocoding API, instead of collecting all results first and sending them in one batch. Let's fix that step by step.

Step 1: Adjust Your JavaScript to Collect Results & Submit in Batch

First, we'll refactor your JS code to gather all resolved geocoding results into an array, then send the entire list to your controller once all API calls are done. Here's a revised example:

// Assume you have an array of addresses extracted from your Excel file
const addresses = ["123 Main St, New York", "456 Oak Ave, Los Angeles", ...]; // Replace with your actual Excel data
const geocodedResults = [];
const apiKey = "YOUR_GOOGLE_API_KEY"; // Don't forget to use your valid API key

// Create an array of promises for each geocoding request
const geocodingPromises = addresses.map(address => {
  return axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${apiKey}`)
    .then(response => {
      if (response.data.status === "OK") {
        const location = response.data.results[0].geometry.location;
        // Push the complete address + lat/lng set into our results array
        geocodedResults.push({
          Address: address,
          Latitude: location.lat,
          Longitude: location.lng
        });
      } else {
        console.warn(`Failed to geocode address: ${address} - Status: ${response.data.status}`);
      }
    })
    .catch(error => {
      console.error(`Error processing address ${address}:`, error);
    });
});

// Wait for all geocoding requests to finish, then submit the batch
Promise.all(geocodingPromises)
  .then(() => {
    if (geocodedResults.length > 0) {
      // Send the entire list to your controller in one request
      axios.post("/AddressParser/BatchSaveLatLng", geocodedResults)
        .then(response => {
          console.log("Batch save successful!", response.data);
          // Add user feedback here (e.g., a success alert)
        })
        .catch(error => {
          console.error("Batch save failed:", error);
          // Handle error for the user
        });
    } else {
      console.log("No valid geocoded results to submit.");
    }
  });

Key Changes Here:

  • We use Promise.all() to wait for all geocoding requests to complete before contacting the controller.
  • All valid lat/lng entries are collected into geocodedResults instead of submitting one by one.
  • A single axios.post() sends the entire array to your controller, eliminating duplicate submissions.

Step 2: Update Your ASP.NET MVC Controller to Accept the Batch

Next, create a model to represent the geocoded data, then add an action method that accepts a list of this model.

First, the Model (Add to your Models folder):

public class GeocodedAddress
{
    public string Address { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

Then, the Controller Action:

using System.Collections.Generic;
using System.Web.Mvc;
using YourProjectNamespace.Models;

public class AddressParserController : Controller
{
    // POST: AddressParser/BatchSaveLatLng
    [HttpPost]
    public ActionResult BatchSaveLatLng(List<GeocodedAddress> geocodedAddresses)
    {
        if (ModelState.IsValid && geocodedAddresses != null && geocodedAddresses.Count > 0)
        {
            // Your database save logic goes here
            // Example:
            // foreach (var address in geocodedAddresses)
            // {
            //     db.GeocodedAddresses.Add(address);
            // }
            // db.SaveChanges();

            return Json(new { success = true, message = $"{geocodedAddresses.Count} entries saved successfully." });
        }

        return Json(new { success = false, message = "No valid data to save." });
    }
}

Important Notes:

  • Ensure the URL in your axios.post() call matches your controller's route (e.g., /AddressParser/BatchSaveLatLng).
  • MVC's default model binding will map the JSON array from the frontend directly to the List<GeocodedAddress> parameter as long as property names match exactly.

Bonus: Avoid Google API Rate Limits

Google's Geocoding API has rate limits, so if you're processing a large number of addresses, add small delays between requests to avoid hitting quota limits. Modify the promise creation like this:

const geocodingPromises = addresses.map((address, index) => {
  return new Promise(resolve => {
    setTimeout(() => {
      axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${apiKey}`)
        .then(response => {
          // ... existing geocoding logic ...
          resolve();
        })
        .catch(error => {
          // ... existing error handling ...
          resolve();
        });
    }, index * 1000); // 1 second delay between each request
  });
});

内容的提问来源于stack exchange,提问作者Emre Şükrü Şentürk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:02:46