在我解释我的情况之前,请先看一下非常重要的通知!!
1.我的javascript没有嵌入到.aspx文件中,所以类似于
var strMessage = '<%= str%>';
StartGeocoding(strMessage);
不起作用(我尝试了很多,但如果您可以改进它,请告诉我)
2.另外,我已经用过
Page.ClientScript.RegisterStartupScript( , , , )
函数,所以我认为我不允许使用两次。
================================================== =================
所以,这里 在“Location.js”中(与 .aspx 分开)
function LoadMap(count) {
var asdf = (something variable from code-behind);
var counts = count;
myMap = new VEMap("mapDiv");
myMap.LoadMap();
StartGeocoding(asdf); // it will show the map with location info of "asdf"
}
在代码后面,有一些东西
public string blahblah = "1 Yonge Street"
基本上,我将从后面的代码中获取地址,然后使用 javascript 显示它。 如果你(我的上帝!)可以教我如何从 javascript 获取 C# 中的变量,那将非常感激!!!
如果你们想挑战,这里有奖金(?)问题
实际上,我会在 map 上显示多个位置。因此,我可能有一个字符串列表,而不是一个字符串“blahblah”
<list>Locationlist //not array
因此,LoadMap() 函数中的“计数”将识别我有多少个条目。如何从javascript获取每个位置信息?这可能吗?有什么想法吗?
最佳答案
这就是我的想法。 在代码隐藏中,假设是 Page_Load 方法,您可以使用以下代码:
List<string> locations = new List<string> { "1 Yonge Street", "100 Yonge Street", "123 Microsoft Way" };
//transform the list of locations into a javascript array.
//The generated script should look like window.myLocations = ['1 Yonge Street', '100 Yonge Street', etc];
StringBuilder script = new StringBuilder();
script.Append("window.myLocations = [");
foreach(string location in locations){
if(script.Length > 0){
script.Append(", ");
}
script.Append("'"+System.Web.HttpUtility.JavaScriptStringEncode(location) +"'");
}
script.Append("];");
//then register this script via RegisterStartupScript.
Page.ClientScript.RegisterStartupScript( this, this.GetType(), "registerMyLocations", script.ToString(), true);
此时您可以访问Location.js中注册的数组:
function LoadMap(/*count*/) {
var asdf = window.myLocations[0]; //this would be '1 Yonge Street' in your case
alert(asdf);
//var counts = count;
var counts = window.myLocations.length;
alert(counts);
myMap = new VEMap("mapDiv");
myMap.LoadMap();
StartGeocoding(asdf); // it will show the map with location info of "asdf"
}
一些评论:
要使用 StringBuilder 类,您需要在文件顶部添加“using System.Text”;
需要 System.Web.HttpUtility.JavaScriptStringEncode 来确保服务器端字符串正确编码(取自 Caveats Encoding a C# string to a Javascript string )。据我了解,它仅在 .Net 4 中可用。
如果页面上有 ScriptManager,最好使用 ScriptManager 上的 RegisterStartupScript,而不是 Page.ClientScript 中的方法
我现在无法测试上面的代码,但你应该了解基本的想法。
关于javascript - 从 javascript 访问 C#(代码隐藏)中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10939631/