Vova Potapov Vova Potapov - 1 year ago 232
ASP.NET (C#) Question

How to pass Dictionary from c#(server) to javascript(client)

I have a function in c# that builds dictionary ,I need to pass this dictionary to my java-script function.

This is what I have tried

My server function

public partial class login : System.Web.UI.Page
protected Dictionary<string, string> GetTradingTypeToSelect()
Dictionary<string, string> dict = new Dictionary<string, string>();
try {
string Types =GetString("some text);
var items = Types.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] { '=' }));

foreach (var item in items)
dict.Add(item[1], item[0]);

//this working 100%
catch (Exception ex)

return dict;

My client:

$(document).ready(function () {

$("#Account").keyup(function () {

var TradingTypeToSelect = '<%=GetTradingTypeToSelect();%>';
//TradingTypeToSelect is equals to string '<%=GetTradingTypeToSelect();%>'
var test = TradingTypeToSelect[0].key;
var test2 = TradingTypeToSelect[0].value;



What am I missing here?

Answer Source

You can create a [WebMethod] in the code behind and call it from javascript using $.ajax.Below is a complete example:

Code behind:

public static Dictionary<string, string> GetTradingTypeToSelect()
    var dict = new Dictionary<string, string>();
    dict.Add("1", "Item 1");
    dict.Add("2", "Item 2");
    return dict;


<head runat="server">
    <script src="//code.jquery.com/jquery-1.12.3.min.js"></script>
    <script type="text/javascript">
        $(function () {

            $("#Account").keyup(function () {
                    type: "POST",
                    url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                    error: function (errordata) {
    <form id="form1" runat="server">
        <input id="Account" type="text" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download