在我的MVC 4应用程序中进行了重大重构后,Razor在调试视图时显示了此错误:

当前上下文中不存在名称“model”。

这是有问题的代码行:

@model ICollection<DataSourceByActive>

我知道@model的用法是正确的。

为什么会这样?我该怎么解决呢?


当前回答

在我的案例中,问题是在将项目从MVC 4升级到MVC 5之后,我不知为何错过了Views/web.config中的版本更改:

    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">            

它仍然使用旧的2.0.0.0版本。在将版本更改为3.0.0.0之后,一切都开始正常工作。

此外,由于这个问题,Visual Studio 2015 Community Edition每次打开.cshtml文件时都会开始敲打CPU(空闲时占用30-40%)。

其他回答

把@Model改成@Model对我来说很管用。

@model表示视图模型对象类型。@Model表示视图模型对象。

我找到了解决办法。 如果你想更新razor版本或mvc 4到5,改变一些行。

Views/web.config中的旧代码

<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>

取而代之的是

<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>

sectionGroup也必须更改。

我在nopCommerce中遇到了这个问题,我将插件的视图部分复制到nopCommerce \Plugins下的输出文件夹中,但视图需要是一个嵌入式资源。因此,.csthml文件的错误构建操作是“内容”,而它应该是“嵌入式资源”,不需要复制。

不知为何,我的网。config在oldVersion属性中设置0.0.0.0:

<runtime>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
</runtime>

改变到1.0.0.0是解决方案:

  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
  </dependentAssembly>

您可能会在代码中使用一个名为model的变量。