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

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

这是有问题的代码行:

@model ICollection<DataSourceByActive>

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

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


当前回答

我在Visual Studio 2019中使用了一个MVC4项目,结果发现VS 2019不支持开箱即用的MVC4。你必须安装这个。

步骤:

打开Visual studio安装程序(在windows中搜索Visual studio安装程序) 单击各个组件 在搜索框中输入“mvc” 检查mvc4-box 点击右下角的“修改”

注意:需要关闭视觉工作室

其他回答

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

确保在你的网站上都有以下内容。配置和视图目录Web。在appSettings部分配置

<add key="webpages:Version" value="2.0.0.0" />

MVC5使用:

<add key="webpages:Version" value="3.0.0.0" />

(而且它只存在于主Web中。配置文件)。

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

这里似乎有3个版本号设置需要彼此正确:

…包含。= . x.x.x Mvc,版本。x……(在各个地方~\Views\web.config) …System.Web.WebPages。= . x.x.x剃须刀,版本。x……(在各个地方~\Views\web.config) <add key="webpages:Version" value=" x.x.x.x。"x" />(在~\web.config中

对我有用的组合:

组合1:

包含。= 4.0.0.0 Mvc,版本

System.Web.WebPages。剃须刀,版本= 2.0.0.0之间

<add key="webpages:Version" value="2.0.0.0" />

结合2:

包含。= 5.2.7.0 Mvc,版本

System.Web.WebPages。= 3.0.0.0剃须刀,版本

<add key="webpages:Version" value="3.0.0.0" />

最后一个观察是网页:版本设置似乎是可选的。删除它似乎没有负面影响,至少在当前问题的背景下是这样。

在web中更改下面的行。配置视图文件夹解决了同样的错误。

From

 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.2.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

To

<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />