I was wondering if Razor views could be compiled, like WebForm based views?
Does it even make sense to compile Razor views and why would somebody want to do that?
Razor files with a . cshtml extension are compiled at both build and publish time using the Razor SDK. Runtime compilation may be optionally enabled by configuring the project.
cshtml files will be compiled just-in-time, that is when a request arrives regarding those pages. However controllers are pre-compiled and stored into your project's DLL files.
You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.
Razor Pages is sometimes described as implementing the MVVM (Model, View ViewModel) pattern. It doesn't. The MVVM pattern is applied to applications where the presentation and model share the same layer. It is popular in WPF, mobile application development, and some JavaScript libraries.
Edit:
Here is a blog post on this topic as well:
How to Detect Errors of Our ASP.NET MVC Views on Compile Time
To make your views to be compiled, do the following;
see the following code;
<!--There some lines of code here and I deleted them to get to the point quickly--> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <MvcBuildViews>false</MvcBuildViews>
change the MvcBuildViews tag value from false
to true
after that save it and reload your project.
after you build your solution to compile it, you will see that your view will be compiled too.
NOTE: to test it, break some code in one of your view on purpose and try to build. you will see that you'll get an error message.
The MvcBuildViews check is excellent but it adds a 5-10 second penalty for building your web app if it's complex enough. It doesn't cache the compilation output so it does a full compilation of all your views every time.
I found a nice compromise by following the above advice and adding a Condition attribute:
<MvcBuildViews Condition=" '$(Configuration)' == 'Release' ">true</MvcBuildViews>
We'd expect ReSharper to flag up any errors in the views anyway and the developer can always build in the release configuration as a test - we have a "preflight" script that developers run so they can easily make sure that package targets work and so on - and if all that fails, the build server will catch it.
Perhaps this trick is obvious but I've only really started learning about msbuild properly as opposed to writing Powershell scripts for these tasks. I hope this is helpful to someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With