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

ASP.NET Core MVC中_ViewImport.cshtml导入无效,视图模型报错

ASP.NET Core MVC 视图中Product模型引用错误问题

开发ASP.NET Core MVC Web应用时,已在_ViewImport.cshtml中导入IdentityApp.Models命名空间,但视图内的Product模型仍出现引用错误。

相关代码

Product模型类

namespace IdentityApp.Models {
    public class Product {
        public long Id { get; set; }
        public string Name { get; set; }
        [Column(TypeName = "decimal(8, 2)")]
        public decimal Price { get; set; }
        public string Category { get; set; }
    }
}

_ViewImport.cshtml 内容

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.AspNetCore.Identity
@using System.Security.Claims
@using IdentityApp.Models

Home/Index.cshtml 视图代码

@model IQueryable<Product>

<h4 class="bg-primary text-white text-center p-2">MVC - Level 1 - Anyone</h4>

<div class="text-center">
    <h6 class="p-2">The store contains @Model.Count() products.</h6>
</div>

错误截图

错误截图

解决方法

  1. 确认_ViewImport.cshtml位置:必须放在Views文件夹根目录,子文件夹内的_ViewImport仅作用于当前子文件夹,无法全局导入命名空间。
  2. 清理重建项目:清除项目缓存,右键项目选择「清理」,再执行「生成」,必要时重启Visual Studio。
  3. 校验命名空间拼写:C#大小写敏感,确保IdentityApp.Models的拼写(包括大小写)在模型类和_ViewImport中完全一致。
  4. 临时显式导入测试:在Index视图顶部添加@using IdentityApp.Models,若错误消失,说明全局导入未生效,需排查_ViewImport的作用范围。
  5. 检查项目引用:如果是多项目解决方案,确认Product模型所在的项目已被当前Web项目正确引用。

内容的提问来源于stack exchange,提问作者Assay Khan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 06:52:24