使用JSON字符串填充ASP.Net DropDownList

时间:2014-07-16 11:44:21

标签: c# asp.net json dictionary

如何从json字符串中获取某些值,并将其插入C#中的字典?

以下是我的json字符串:

[{"RowNum":7,"Item_Code":"m2","Item_Name":"Mixer","Item_ProductBrand":0,"Item_Category":1,"Item_Unit":0,"Item_Blocked":false,"Costing_Method":0,"Standard_Cost":0.0,"Retail_UnitPrice":10.0,"Dealer_UnitPrice":20.0,"Distributor_UnitPrice":30.0,"Safety_Stock":0.0,"Safety_LeadTime":0,"Reorder_Point":0.0,"Reorder_Quantity":0.0,"BusinessUnitID":"1","CompanyID":"1","RowVersion":1},{"RowNum":8,"Item_Code":"t1","Item_Name":"Television","Item_ProductBrand":0,"Item_Category":1,"Item_Unit":0,"Item_Blocked":false,"Costing_Method":0,"Standard_Cost":0.0,"Retail_UnitPrice":40.0,"Dealer_UnitPrice":50.0,"Distributor_UnitPrice":60.0,"Safety_Stock":0.0,"Safety_LeadTime":0,"Reorder_Point":0.0,"Reorder_Quantity":0.0,"BusinessUnitID":"1","CompanyID":"1","RowVersion":1}]

目前我在这个字符串中有两个json对象。它实际上是以JSON Array形式创建的字符串。

我有一个字典,我需要在其中添加Item_Name和Item_Code。怎么做?

我成功创建了Dictionary并从字符串中添加/映射元素。但是,我无法填充DropDownList。我的代码是:

string items = GetJSON(url);
Dictionary<string, string>[] itemDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(items);
DropDownList3.DataSource = itemDictionary;
DropDownList3.DataTextField = "Item_Name";
DropDownList3.DataValueField = "Item_Code";
DropDownList3.DataBind();

这不起作用。如何纠正这个?

1 个答案:

答案 0 :(得分:2)

你应该创建一个列表,你不应该将字典绑定到组合框,我不认为你甚至可以。可能是我错了,但这不是干净的方式。所以你可以做的是创建一个对象列表,并从字典中创建一个对象,例如类似于我在下面写的Item对象,然后将该对象添加到列表中。最后将列表设置为数据源。那可行。像这样的东西:

public class item
{
    public Customer(){
    }

    public int ItemCode{set; get;}
    public string ItemName{set; get;} 

   // and the other properties 

} 

然后从dictonary创建对象并将其添加到列表中。

List<Item> itemList = new List<Item>();
string items = GetJSON(url);
Dictionary<string, string>[] itemDictionary = JsonConvert.DeserializeObject<Dictionary<string, string>[]>(items);
Item newItem = new Item();
newmItem.ItemCode = Convert.ToInt32 (itemDictionary["Item_Code"]); 
// ... and the other properties 
// then add the object to the list 
itemList.Add(newItem);
DropDownList3.DataSource = itemList;
DropDownList3.DataTextField = "ItemName";

DropDownList3.DataBind();

然后将它绑定到index_changed事件并从那里将其转换为Item对象并获取您感兴趣的属性