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

ASP.NET Core MVC项目运行报错:无法转换Root类型为IEnumerable

问题解决思路

核心错误原因

控制器返回的是单个Root对象,但视图声明的模型是IEnumerable<Final_Project.Models.Root>(Root的集合),类型不匹配导致转换失败;同时视图循环逻辑错误,没有遍历Root内部的cards集合(实际要展示的卡片数据)。


具体修改步骤

1. 修正视图的模型声明

将视图顶部的模型声明从集合改为单个Root对象:

@model Final_Project.Models.Root

2. 修正视图的循环逻辑

Root里的cards属性才是需要展示的Result集合,循环时要遍历Model.cards,同时增加空值判断避免异常:

<h2>Card Info</h2>

<div style="display: block">
    <a href="/Card/DispayCard/">Card Information</a>
</div>

<table class="table" >
    <tr>
        <th>Name</th>
        <th>Variant</th>
        <th>Card Number</th>
        <th>Rarity</th>
        <th>Card ID</th>
    </tr>

    @if (Model?.cards != null)
    {
        foreach (var card in Model.cards)
        {
            <tr>
                <td><a href="/CardInfo/ViewProduct/@card.name">@card.name</a></td>
                <td>@card.variant</td>
                <td>@card.cardNumber</td>
                <td>@card.rarity</td>
                <td>@card.cardId</td>
            </tr>
        }
    }
    else
    {
        <tr>
            <td colspan="5">暂无卡片数据</td>
        </tr>
    }
</table>

(注:已修正原视图中重复的name列,匹配正确的字段映射)

3. 控制器健壮性优化(可选)

增加空值处理,避免API返回空数据或反序列化失败导致视图报错:

using Final_Project.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RestSharp;

namespace Final_Project.Controllers
{
    public class CardController : Controller
    {
        public ActionResult Card()
        {
            var client = new RestClient("https://pokemon-tcg-card-prices.p.rapidapi.com/card?name=Arcues%20V");
            var request = new RestRequest();

            // 确保填写正确的API密钥和Host
            request.AddHeader("X-RapidAPI-Key", "你的API密钥");
            request.AddHeader("X-RapidAPI-Host", "pokemon-tcg-card-prices.p.rapidapi.com");

            var response = client.Execute(request).Content;

            // 处理响应为空的情况
            if (string.IsNullOrEmpty(response))
            {
                return View(new Root { cards = new List<Result>() });
            }

            Root cards = JsonConvert.DeserializeObject<Final_Project.Models.Root>(response);
            
            // 确保Root和cards集合不为null
            cards ??= new Root { cards = new List<Result>() };
            cards.cards ??= new List<Result>();

            return View(cards);
        }
    }
}

4. 额外检查点

  • 确认API密钥和Host已正确填写,否则API会返回错误或空数据;
  • 验证API返回的JSON字段名与你的模型类完全匹配(Newtonsoft.Json默认大小写敏感),如果字段名不一致,需用[JsonProperty]特性指定映射:
    public class Root
    {
        [JsonProperty("cards")] // 匹配API返回的字段名
        public List<Result>? cards { get; set; }
        [JsonProperty("paging")]
        public Paging? paging { get; set; }
    }
    

内容的提问来源于stack exchange,提问作者Randall Smith

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 21:53:25