Category: .NET Core
view more software Tips and Tricks
Updated: 10/22/2017 06:10 AM
Author: Shiju Mathews
_ViewImports.cshtml serves one major purpose: to provide namespaces which can be used by all other views. In previous MVC projects, this functionality was provided by the web.config file in the Views folder; since the web.config no longer exists, global namespaces are now provided by this file. But this chtml file cannot renter any html to the page.
As of Beta 5 of ASP.NET 5, there is a new file in the Views folder of an MVC project called '_ViewImports.cshtml' .
In order to add the file right click on the project and select Add >> New Item and select "MVC View Imports Page"
The new page will be added with the content as bellow
The first two lines are fairly easy to understand:
we want the MyProject.Web and Microsoft.Framework.OptionsModel namespaces to be available to all views. If we wanted another namespace to be available, we'd simply add it here.
Any 'ViewModel' that is using in a view need to be declared in the view page as follows.
In case we need to use this "ViewModel" in different views or different 'view model' from the same name space in using in different views, we can move the name space declaration in the "_ViewImports.cshtml as follows.
Now we can eliminate the namespace declaration in view page.