Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 324
Vladimir Potapov Avatar asked Oct 18 '25 07:10

Vladimir Potapov


1 Answers

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 () {
                $.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>
like image 103
Denys Wessels Avatar answered Oct 19 '25 20:10

Denys Wessels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!