Vova Potapov Vova Potapov - 3 months ago 29
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

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

Code behind:

[System.Web.Services.WebMethod]
public static Dictionary<string, string> GetTradingTypeToSelect()
{
    var dict = new Dictionary<string, string>();
    dict.Add("1", "Item 1");
    dict.Add("2", "Item 2");
    return dict;
}

.ASPX:

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

            $("#Account").keyup(function () {
                alert('up');
                $.ajax({
                    type: "POST",
                    url: "AjaxCallExample.aspx/GetTradingTypeToSelect",
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        alert(data.d["1"]);
                        alert(data.d["2"]);
                    },
                    error: function (errordata) {
                        console.log(errordata);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <input id="Account" type="text" />
    </form>
</body>
Comments