In this article, we'll introduce Razor View Import. In addition to the ViewStart file, there is also a ViewImports file that the MVC framework looks for when rendering any view.
As with the ViewStart file, we can drag and drop ViewImports.cshtml into the folder, the ViewImports file can affect all views in the folder hierarchy
This view is a new view for this version of MVC, in previous MVC versions we could use XML configuration files to configure certain aspects of the Razor view engine.
Those XML files are now gone, and we use code instead.
The ViewImports file is where we can write code and place generic instructions to bring in the namespace we need for our views.
If there is, we usually use the namespace in our view, we can use the directive in the ViewImports file once we appear, rather than using the full namespace in each view or type of type.
Example
Let's take a simple example to see how to move the using directive into ViewImports. In the Index view, we have a using command to bring in the namespace FirstAppDemo.Controllers, as shown in the program below.
Using directives will allow the code generated from the Razor view to compile correctly. Without using directives, the C# compiler will not be able to find this Employee type. To see the employee type, let's remove the using directive from the Index.cshtml file.
Now, run the app.
You will see an error stating that the type or namespace HomePageViewModel cannot be found. Probably because several of your views require the same using directive. So let's create a View import in the Views folder instead of putting it in each view. This will add a using statement to each view, just right-click on the Views folder and select Add→New Item.
In the middle pane, select the MVC View Imports page. By default, the name is _ViewImports.cshtml. Just like ViewStart, we can't use this file to render HTML, so let's hit the Add button.
Now add the using directive from this to the _ViewImports.cshtml file as shown below.
Now all views displayed in this folder or any subfolder can use the type in FirstAppDemo.Controllers without specifying a precise using statement. Let's run your app again and you can see that view is now running.
|