简体   繁体   English

使用jQuery在asp.net中访问字典

[英]accessing dictionary in asp.net using jquery

Hi I declared a dictionary in .cs file of asp.net but I want to access the contents of this dictionary by using a jquery function. 嗨,我在asp.net的.cs文件中声明了一个字典,但是我想使用jquery函数访问该字典的内容。 The jquery function takes key as input and in the body of the function it should access the dictionary in the .cs of asp.net and process it and jquery should output the value corresponding to the key. jquery函数将key作为输入,并且在函数的主体中,它应该访问asp.net .cs中的字典并对其进行处理,并且jquery应该输出与key对应的值。 Can you suggest a way to do this. 您能建议一种方法吗?

The code which I a writing is 我写的代码是

public string DictJson { 
   get { 
      MouseOverFieldDict mdict = new MouseOverFieldDict(); 
      JavaScriptSerializer jSer = new JavaScriptSerializer(); 
      return jSer.Serialize(mdict.FieldDict); 
   } 
} 

I added above code in .cs file as a property and I tried to access it in the script which I wrote in aspx page 我在.cs文件中将上述代码添加为属性,并尝试在我在aspx页面中编写的脚本中访问它

var dict = $.parseJSON('<%=DictJSON %>'); 
alert(dict); 

but I'm getting error The name 'DictJSON' does not exist in the current context . 但我收到错误消息'DictJSON'在当前上下文中不存在。 The error is showing for DictJSON declared in the script part 对于脚本部分中声明的DictJSON,显示错误

Your casing is incorrect - should be DictJson , not DictJSON . 您的大小写不正确-应该是DictJson ,而不是DictJSON Inside the code block in your page, the code is C#, so it's case-sensitive. 在页面的代码块中,代码是C#,因此区分大小写。

Additionally, since you're returning a JSON string, you really don't need to put it in quotes and then parse it - in fact, there's a good chance that won't work. 此外,由于返回的是JSON字符串,因此您实际上不需要将其放在引号中然后进行解析-实际上,很有可能不起作用。 You can instead do either: 您可以执行以下任一操作:

var dict = <%= DictJson %>;

or you can do something a little different if you don't want to mix your server and client scripts together: 或者,如果您不想将服务器和客户端脚本混合在一起,则可以做一些不同的事情:

<script type="application/json" id="dict-contents">
    <%= DictJson %>
</script>

<script type="text/javascript">
    var dict = JSON.parse(jQuery("#dict-contents").html());
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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