简体   繁体   English

如何将字典从C#(服务器)传递到javascript(客户端)

[英]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. 我在c#中有一个构建字典的函数,我需要将此字典传递给我的Java脚本函数。

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? 我在这里想念什么?

You can create a [WebMethod] in the code behind and call it from javascript using $.ajax .Below is a complete example: 您可以在后面的代码中创建[WebMethod]并使用$.ajax从javascript调用它。以下是一个完整的示例:

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: .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>

How about exposing the dictionary in the view model: 如何在视图模型中公开字典:

public Dictionary<string, string> TradingTypesToSelect { get; set; }

And iterate over the dictionary inside the <script> block, creating a JavaScript associative array, like so: 然后遍历<script>块中的字典,创建一个JavaScript关联数组,如下所示:

<script>
    var tradingTypesToSelect = {};
    <% foreach (var tradingType in Model.TradingTypesToSelect) { %>
        tradingTypesToSelect["<%= tradingType.Key %>"] = "<%= tradingType.Value %>";
    <% } %>
</script>

At least this way you don't have to make another call (via AJAX) to retrieve additional data. 至少通过这种方式,您不必(通过AJAX)再次调用即可检索其他数据。

I believe you need to make a WebMethod to enable the server function to be called from the client side. 我相信您需要创建一个WebMethod来启用从客户端调用服务器功能。 Here is an example: Calling ASP.Net WebMethod using jQuery AJAX 这是一个示例: 使用jQuery AJAX调用ASP.Net WebMethod

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

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