简体   繁体   中英

how to get Javascript variable value in C#

I have two Lat/long tables, 1000 rows each table. I wanted to calculate the distance between two latitude/longitude using Google Map API and store distance in DB. The code is working fine but the catch is how to return calculated distance from javascript. I tried hidden fields to store the distance since I have written the below code in page load, but it's not working:

        SqlConnection sql_con = new SqlConnection("Database=myDB;Server=mySever;User Id=myID;password=PWD");
        SqlCommand sql_cmd = new SqlCommand("select Zip,Latitude,Longitude from ZipCodes", sql_con);
        SqlDataAdapter sql_adt = new SqlDataAdapter(sql_cmd);
        DataSet dsZip = new DataSet();
        sql_adt.Fill(dsZip);

        sql_cmd = new SqlCommand("select * from MyPlaceLatLong", sql_con);
        sql_adt = new SqlDataAdapter(sql_cmd);
        DataSet dsStore = new DataSet();
        sql_adt.Fill(dsStore);

        for (int zcnt = 0; zcnt < dsZip.Tables[0].Rows.Count; zcnt++)
        {
            for (int i = 0; i < dsStore.Tables[0].Rows.Count; i++)
            {
                Page.ClientScript.RegisterClientScriptBlock(GetType(), "myScssript", "<script>" +
                 "var origin1 = new google.maps.LatLng("+dsZip.Tables[0].Rows[zcnt]["Latitude"].ToString()+","+ dsZip.Tables[0].Rows[zcnt]["Longitude"].ToString()+");" +
                 "var origin2 = new google.maps.LatLng(" + dsStore.Tables[0].Rows[i]["lat"].ToString() + "," + dsStore.Tables[0].Rows[i]["long"].ToString() + ");" +
                  //"var origin1 = new google.maps.LatLng(55.930385, -3.118425);" +
                  //"var origin2 = new google.maps.LatLng(51.483061, -0.004151);" +
                 "var service = new google.maps.DistanceMatrixService();" +
                 " alert('Made it to calculateDistances');" +
                 "service.getDistanceMatrix(" +
                 "{" +
                   "origins: [origin1]," +
                   "destinations: [origin2]," +
                   "travelMode: google.maps.TravelMode.DRIVING," +
                   "unitSystem: google.maps.UnitSystem.IMPERIAL," +
                   "avoidHighways: false," +
                   "avoidTolls: false" +
                 "}, callback);" +
                 "function callback(response, status)" +
                   "{" +
                    "if (status == google.maps.DistanceMatrixStatus.OK) { " +
                    "var origins = response.originAddresses;   " +
                    "var destinations = response.destinationAddresses;" +
                    "for (var i = 0; i < origins.length; i++) {" +
                    "var results = response.rows[i].elements;" +
                    "for (var j = 0; j < results.length; j++) {" +
                    "var element = results[j];" +
                    "var distance = element.distance.text;" +
                    "var duration = element.duration.text; " +
                    "var from = origins[i];" +
                    "var to = destinations[j];" +
                   "alert('The distance:'+ distance);" +
                    "}}}}" +
               "</script>");



            }
        }

You need to set the value of the hidden field in your JavaScript, which I don't believe I see in there. Declare the field in your ASP like this:

<input type="hidden" id="txtDistance" runat="server" />

In your JavaScript add this towards the end of your "function callback(response, status)" :

 document.getElementById("txtDistance").value = distance;

And then in your C# code, you can access this value like so:

string cDistance = txtDistance.Value;

//Original text was string cDistance = txtDistance.value;

Hope that helps.

This is what I used with full success.

https://stackoverflow.com/a/44570554/7991036

To provide with more details, I wrote a class based on the standard WebBrowser . Within this class, I added the following method:

/// <summary>
/// Execute and get the returned value from the JavaScript into HTML page without appending it.
/// </summary>
/// <param name="strJS">JavaScript to execute.</param>
/// <returns>Dynamic result depending on JavaScript function code.</returns>
public dynamic JSExecuteAndReturnVal(string strJS)
{
    dynamic dynResult = Document.InvokeScript("eval", new[] { strJS });

    return dynResult;
}

Each time I need some value from JavaScript code, I'm using this method as far as the class is navigating to relevant web page. The method is accepting any kind of pure JavaScript code so that it can return any kind of value, directly depending on the code.

Here is for instance how to use the method:

string strClassName = "whatever";
string strJS = "function JSDoIt(){objResult = document.getElementsByClassName('" + strClassName + "')[0]." +
"textContent; return { Result: objResult }; }; JSDoIt();";
dynamic dynJSResult = myWebBrowser.JSExecuteAndReturnVal(strJS);
decimal.TryParse(dynJSResult.Result.ToString(), out decimal nTotal);

The trick is to use a structured object to return value(s). On the C# code side, then you do need to keep this in mind to get properly the value well returned.

With this sample, you don't need to hide any HTML object in any web page to then grab results from any JavaScript function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM