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

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

这是有问题的代码行:

@model ICollection<DataSourceByActive>

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

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


当前回答

不知为何,我的网。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>

其他回答

我试图添加一个视图,这是我的“视图”文件夹(只是组织我的代码不同,我猜),当我有这个问题。在Views中创建视图(按照惯例)解决了这个问题。

在我的例子中,下面的代码被认为是有用的。放在下面的网页代码。“视图”文件夹下的config文件。

<configSections>

  <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>

</configSections>

一旦代码更新,请确保清理并重新构建解决方案。我希望这对你有所帮助!

对我来说,问题是我最近导入的一个库中的. net版本冲突。我导入的库是为4.5.2和ASP。NET MVC站点我把它导入了目标4.5。重新编译后说库4.5网站将编译。

此外,没有编译错误,但这个问题被报告为“警告”。因此,如果有任何警告,请务必阅读所有警告。

在我的案例中,问题是在将项目从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的变量。