我想綁定asp:dropdownlist與json數據使用JsonConvert.DeserializeObject
,它是獲取完整的json,但我想要綁定它與json數據的內部數組。獲取的數據類型爲{System.Collections.ListDictionaryInternal}
,並且綁定時拋出異常{"Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource."}
。「{」數據源是無效類型。它必須是IListSource,IEnumerable或IDataSource。「}」綁定
ddlCategoryMain
是完全結合,
異常在ddlCategoryMain_SelectedIndexChanged
這裏結合ddlCategorySub
是JSON數據:
{
"Category": [
{
"MainCategory": "Biography",
"SubCategory": [
"Historical",
"Political",
"Military",
"Musician"
]
},
{
"MainCategory": "Business",
"SubCategory": [
"Self-Employed",
"Taxation",
"Personal Finance",
"Organisational Behaviour"
]
},
{
"MainCategory": "Computers & Internet",
"SubCategory": [
"Computer Programing",
"Web Design",
"Mobile Phones",
"Computer Hardware",
"Operating Systems"
]
}
]
}
這裏是DataEntity:
public class bookcategoryDE
{
public List<Category> Category { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
public string MainCategory { get; set; }
public List<string> SubCategory { get; set; }
}
這是我的代碼:
(的.aspx):
<asp:DropDownList ID="ddlCategoryMain" runat="server" DataTextField="MainCategory" DataValueField="MainCategory"
AutoPostBack="true" OnSelectedIndexChanged="ddlCategoryMain_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<asp:DropDownList ID="ddlCategorySub" runat="server" DataTextField="SubCategory" DataValueField="SubCategory"></asp:DropDownList>
(的.cs):
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var JsonBookCategory = ReadJson<bookcategoryDE>(Server.MapPath("~/Json/Category.json"));
ddlCategoryMain.DataSource = JsonBookCategory.Category;
ddlCategoryMain.DataBind();
}
}
public T ReadJson<T>(string JsonPath)
{
using (StreamReader r = new StreamReader(JsonPath))
{
T keys = JsonConvert.DeserializeObject<T>(r.ReadToEnd());
return keys;
}
}
protected void ddlCategoryMain_SelectedIndexChanged(object sender, EventArgs e)
{
var JsonBookCategory = ReadJson<bookcategoryDE>(Server.MapPath("~/Json/Category.json"));
ddlCategorySub.DataSource = JsonBookCategory;
ddlCategorySub.DataBind();
}
正在返回什麼通過'ReadJson'方法? –