如何在C#中获取Javascript变量值

时间:2012-09-02 05:59:19

标签: c# javascript

我有两个Lat / long表,每个表1000行。我想使用Google Map API计算两个纬度/经度之间的距离,并在DB中存储距离。 代码工作正常,但问题是如何从javascript返回计算的距离。我尝试隐藏字段来存储距离,因为我在页面加载中编写了下面的代码,但它不起作用:

        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>");



            }
        }

2 个答案:

答案 0 :(得分:5)

您需要在JavaScript中设置隐藏字段的值,我不相信我在那里看到的。在ASP中声明字段如下:

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

在你的JavaScript中,在你的“函数回调(响应,状态)”结束时添加它:

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

然后在您的C#代码中,您可以像这样访问此值:

string cDistance = txtDistance.value;

希望有所帮助。

答案 1 :(得分:0)

这是我获得圆满成功的方式。

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

为了提供更多细节,我基于标准WebBrowser编写了一个类。在此类中,我添加了以下方法:

/// <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;
}

每次我需要从JavaScript代码中获取一些价值时,只要该类正在导航到相关的网页,我都会使用此方法。该方法接受任何种类的纯JavaScript代码,以便它可以直接取决于代码而返回任何种类的值。

例如,这里是方法的使用方法:

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);

诀窍是使用结构化对象返回值。在C#代码方面,那么您确实需要牢记这一点,以便正确获取正确返回的值。

使用此示例,您无需在任何网页中隐藏任何HTML对象即可从任何JavaScript函数中获取结果。