Razor 视图查找没有完整路径的 ViewModel

Razor view finding ViewModel without full path

对ASP.NET还是个新手,所以请原谅我的问题很简单。

我正在 ASP.NET MVC Core 2 中编写演示应用程序。对于我的视图,我引用了 ViewModel 的完整路径,例如:

@model MyApp.ViewModels.ProductDetailViewModel

我正在遵循的一个解决方案是使用一些巫术,它在没有完整路径的情况下引用它的 ViewModels:

@model ProductDetailViewModel

我不介意使用完整路径,我只是想知道演示项目是如何做到的。我没有看到任何关于它是如何完成的明显线索。

这可能是因为演示项目将添加命名空间。它在 web.config 中完成,通常在 Views 文件夹中。会有这样一行:

<system.web.webPages.razor>
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="MyApp.ViewModels" /> <!--- this line

对于 ASP.Net Core,导入是在 Views 文件夹中的 _ViewImports.cshtml 文件中完成的。添加这样一行:

@using MyApp.ViewModels