You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GridView绑定WebAPI数据报错:无属性生成列,数据无法显示

解决GridView绑定WebAPI数据时“无可用属性生成列”的错误

你遇到的错误根源在于:将WebAPI返回的JSON反序列化为JArray(动态JSON数组)后,ASP.NET GridView无法识别JObject的动态属性,因此无法生成对应的列。以下是两种可行的解决方案:


方案1:使用强类型实体类绑定(推荐)

通过定义与API返回数据匹配的实体类,让GridView能识别明确的属性字段。

步骤1:定义Author实体类

public class Author
{
    public int author_id { get; set; }
    public string author_name { get; set; }
    // 若API返回其他字段,需同步添加对应属性
}

步骤2:修改后台Page_Load代码

protected void Page_Load(object sender, EventArgs e)
{
    // 仅首次加载时绑定数据,避免回发重复请求API
    if (!IsPostBack)
    {
        try
        {
            var webRequest = (HttpWebRequest)WebRequest.Create("https://localhost:44342/api/author");
            var webResponse = (HttpWebResponse)webRequest.GetResponse();
            if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
            {
                var reader = new StreamReader(webResponse.GetResponseStream());
                string s = reader.ReadToEnd();
                // 反序列化为强类型列表
                var authorList = JsonConvert.DeserializeObject<List<Author>>(s);
                GridView1.DataSource = authorList;
                GridView1.DataBind();
            }
            else
            {
                MessageBox.Show(string.Format("状态码: {0}", webResponse.StatusCode));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

方案2:将JArray转换为DataTable绑定(无需强类型)

如果不想定义实体类,可以把JArray转换成DataTable,GridView原生支持识别DataTable的列结构:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        try
        {
            var webRequest = (HttpWebRequest)WebRequest.Create("https://localhost:44342/api/author");
            var webResponse = (HttpWebResponse)webRequest.GetResponse();
            if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
            {
                var reader = new StreamReader(webResponse.GetResponseStream());
                string s = reader.ReadToEnd();
                var arr = JsonConvert.DeserializeObject<JArray>(s);
                // 将JArray转为DataTable
                DataTable dt = JsonConvert.DeserializeObject<DataTable>(arr.ToString());
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            else
            {
                MessageBox.Show(string.Format("状态码: {0}", webResponse.StatusCode));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

额外检查点

  • 确认WebAPI返回的字段名与GridView中BoundField的DataField完全一致(比如author_id、author_name)
  • 可以临时打印API返回的s值,验证是否为有效JSON数据
  • 必须保留!IsPostBack判断,避免页面回发时重复请求API

内容的提问来源于stack exchange,提问作者Anusha Saad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:00:53