为何Razor Page出现CS0246错误?添加using语句仍无效
解决Razor Page中CS0246类型找不到错误
我在Razor Page开发中遇到了CS0246错误(找不到类型或命名空间名称“ContatoModel”),已经尝试在代码中添加using ContatoModel;语句,但问题依然存在,希望能解决这个错误,让项目正常构建运行。
错误相关信息
错误截图显示CS0246编译错误,提示无法找到ContatoModel类型。
自动生成的Razor编译代码如下:
#pragma checksum "C:\Users\Nathan\Documents\ASPNET PJ\Views\Contato\Criar.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "0419d52b5c6c647b8ba18e9d7de1b5045cdb5bb3" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Contato_Criar), @"mvc.1.0.view", @"/Views/Contato/Criar.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; using ContatoModel; #nullable restore #line 1 "C:\Users\Nathan\Documents\ASPNET PJ\Views\_ViewImports.cshtml" using ASPNET_PJ; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\Nathan\Documents\ASPNET PJ\Views\_ViewImports.cshtml" using ASPNET_PJ.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"0419d52b5c6c647b8ba18e9d7de1b5045cdb5bb3", @"/Views/Contato/Criar.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"30bddb7a998eb7023ecaaf3235c8530011feaaed", @"/Views/_ViewImports.cshtml")] #nullable restore public class Views_Contato_Criar : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<ContatoModel> #nullable disable
排查与解决步骤
- 确认
ContatoModel的命名空间:检查你的ContatoModel类文件,看它的命名空间是否为ContatoModel,还是属于ASPNET_PJ.Models这类已导入的命名空间。如果是后者,无需单独添加using ContatoModel;,反而要确保视图里的模型引用对应正确命名空间。 - 检查项目引用:如果
ContatoModel类在单独的类库项目中,右键当前Web项目→添加→项目引用,勾选包含该模型的类库。 - 清理重建项目:
- 右键解决方案→清理解决方案
- 删除项目目录下的
bin和obj文件夹 - 右键解决方案→重建解决方案
- 修正视图模型声明:在
Criar.cshtml顶部,将模型声明改为@model 正确命名空间.ContatoModel,例如如果类在ASPNET_PJ.Models下,就写@model ASPNET_PJ.Models.ContatoModel。 - 检查_ViewImports.cshtml:确认文件中导入的命名空间覆盖了你的模型类,比如
@using ASPNET_PJ.Models已经存在的话,视图中可以直接使用ContatoModel而无需额外using。
内容的提问来源于stack exchange,提问作者Nathan Camargo
相关产品推荐
相关产品推荐

