im useless
im useless

Reputation: 7461

How to pass Dictionary<string, string> variable from code behind to asp.net?

Im trying to pass public dictionary from c# to asp.net.

Here's my code:

Code Behind:

public Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
          RetrieveDataField();
        }
    }

 void RetrieveDataField()
{

    DataDefinitionResponse[] _dr = _service.DataDefinitionList(_companyID);

    DataTable dt = new DataTable();
    dt.Columns.Add("Name");
    dt.Columns.Add("Type");

    foreach (DataDefinitionResponse dr in _dr)
    {
        if (dr.Type != "Group" && dr.Type != "File")
        {
            DataRow row = dt.NewRow();
            row["Name"] = dr.Name;
            row["Type"] = dr.Type;
            dt.Rows.Add(row);
            if (dr.Type == "Dropdown")
            {
                string[] strSplit = dr.ListValue.Split('|');
                List<string> lst = new List<string>();

                foreach (string word in strSplit)
                {
                    lst.Add(word);
                }
                dict.Add(dr.Name, lst);
            }
        }
    }

    ddlFieldName.DataSource = dt;
    ddlFieldName.DataTextField = "Name";
    ddlFieldName.DataValueField = "Type";
    ddlFieldName.DataBind();


}

ASP:

<script  type="text/javascript">
    $(document).ready(function () {

        alert(<%=dict%>); //Error here
        $("#MainContent_ddlFieldName").live("change", function () {
            $.ajax({
                type: "POST",
                url: "WebService/WebFunction.asmx/PopulateDropdown",
                data: "{'dict': '" + 'a' + "'}",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (data) {
                   // data.d;
                    // $("#txtBLShipperContactNo").val(data.d);
                    alert(data.d);

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("Error Shipper: " + errorThrown);
                }
            });

        });
    });
</script>

Any thoughts?

Upvotes: 4

Views: 4201

Answers (2)

Mark
Mark

Reputation: 8441

I don't really know the error generated by your codes but here's what I know. The dictionary should be added or 'binded' like this:

DataTable dt = new DataTable();
Dictionary<string,string> dict = new Dictionary<string,string>();
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Type", typeof(string)));

foreach (DataDefinitionResponse dr in _dr)
{
    if (dr.Type != "Group" && dr.Type != "File")
    {
        DataRow row = dt.NewRow();
        row["Name"] = dr["Name"].toString();
        row["Type"] = dr["Key"].toString;
        dt.Rows.Add(row);
    }
}

foreach(DataRow dr in dt.Rows)
{
    dict.Add(dr.ItemArray[0].ToString(), dr.ItemArray[1].ToString());
}

ddlFieldName.DataSource = dict; // the dictionary should be here
ddlFieldName.DataTextField = "Key";
ddlFieldName.DataValueField = "Value";
ddlFieldName.DataBind();

or do the adding of the Dictionary element inside the 1st foreach loop like this:

foreach (DataDefinitionResponse dr in _dr)
    {
        if (dr.Type != "Group" && dr.Type != "File")
        {
            DataRow row = dt.NewRow();
            row["Name"] = dr["Name"].toString();
            row["Type"] = dr["Key"].toString();
            dt.Rows.Add(row);

            dict.Add(dr["Key"].ToString(), dr["Name"].ToString());
    }
}
ddlFieldName.DataSource = dict; // the dictionary should be here
ddlFieldName.DataTextField = "Key";
ddlFieldName.DataValueField = "Value";
ddlFieldName.DataBind();

UPDATE

You are declaring or initialize your column in the wrong way. You can try my update.

Upvotes: 1

Michael Bray
Michael Bray

Reputation: 15275

When you use <%=dict%> the compiler is executing the default ToString() method on that, so you get something like alert(System.Collections.Generic.Dictionary...);. Notice that there are no quotes around this, so it generates a javascript error. You can "fix" this by surrounding it in quotes: alert("<%=dict%>");.

However, this probably isn't what you want to do. You most likely are trying to get the actual dictionary into a Javascript object. To do that, you can use javascript's JSON.parse and System.Web.Script.Serialization.JavaScriptSerializer to output the data as a JSON object. If you are using jQuery then you can use parseJSON, otherwise you can use JSON.parse on most browsers, I think (I always use jQuery, so I'm more familiar with it than the browser-provided JSON.parse).

Here is some code to output an object to JSON:

public string DictJSON
{
    get { 
        JavaScriptSerializer jSer = new JavaScriptSerializer();
        return jSer.Serialize(dict);
    }
}

and here is how you might consume it, using jQuery:

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

Note that JavaScriptSerializer is part of System.Web.Extensions.dll, so you'll need to add a reference to it. It can't handle all object types, but Dictionary should be ok, as should List. Also, since it outputs JSON object strings in double-quotes, make sure you use single-quotes in parseJSON.

Upvotes: 4

Related Questions