- Modern Web Development with ASP.NET Core 3
- Ricardo Peres
- 724字
- 2021-06-18 18:36:04
View compilation
Normally, a view is only compiled when it is first used—that is, a controller action returns ViewResult. What this means is that any eventual syntax errors will only be caught at runtime when the framework is rendering the page; plus, even if there are no errors, ASP.NET Core takes some time (in the order of milliseconds, mind you) to compile the view. This does not need to be the case, however.
Unlike previous versions, ASP.NET Core 3 does not recompile a view when the Razor file changes, by default. For that, you have to restart your server. If you want to have this behavior back, you need to add a reference to the Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation NuGet package and add the following line to the services configuration:
services
.AddMvc()
.AddRazorRuntimeCompilation();
Or, you may prefer to enable this only for the debug version of your app, which excludes it from production builds. In that case, you can do it like this:
var mvc = services.AddMvc();
#if DEBUG
mvc.AddRazorRuntimeCompilation();
#endif
Or, for a specific environment, you can inject IWebHostEnvironment into your Startup class, store it, and check the current environment before making the call to AddRazorRuntimeCompilation, as follows:
public IConfiguration Configuration { get; }
public IWebHostEnvironment Environment { get; }
public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
this.Configuration = configuration;
this.Environment = environment;
}
var mvc = services.AddMvc();
if (this.Environment.IsDevelopment())
{
mvc.AddRazorRuntimeCompilation();
}
Microsoft makes available a NuGet package, which is Microsoft.AspNetCore.Mvc.Razor.ViewCompilation, that you can add as a reference to your project. After this, you can enable view compilation at publishing time, and currently, the only way to do this is by manually editing the .csproj file. Look for the first <PropertyGroup> instance declared in it, the one that contains the <TargetFramework> element, and add a <MvcRazorCompileOnPublish> and a <PreserveCompilationContext> element. The result should look like this:
<PropertyGroup>
<TargetFramework>netcoreapp3</TargetFramework>
<MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
Now, whenever you publish your project, either using Visual Studio or the dotnet publish command, you will get errors.
The class that is generated for each view exposes a property called Html that is of type IHtmlHelper<T>, T being the type of your model. This property has some interesting methods that can be used for rendering HTML, as follows:
- Generating links (ActionLink, RouteLink)
- Generating forms for a given model or model property (BeginForm, BeginRouteForm, CheckBox, CheckBoxFor, Display, DisplayFor, DisplayForModel, DisplayName, DisplayNameFor, DisplayNameForInnerType, DisplayNameForModel, DisplayText, DisplayTextFor, DropDownList, DropDownListFor, Editor, EditorFor, EditorForModel, EndForm, Hidden, HiddenFor, Id, IdFor, IdForModel, Label, LabelFor, LabelForModel, ListBox, ListBoxFor, Name, NameFor, NameForModel, Password, PasswordFor, RadioButton, RadioButtonFor, TextArea, TextAreaFor, TextBox, TextBoxFor, Value, ValueFor, ValueForModel)
- Displaying validation messages (ValidationMessage, ValidationMessageFor, ValidationSummary)
- Rendering anti-forgery tokens (AntiForgeryToken)
- Outputting raw HTML (Raw)
- Including partial views (Partial, PartialAsync, RenderPartial, RenderPartialAsync)
- Getting access to the context properties (ViewContext, ViewBag, ViewData, TempData) and also the base classes' (RazorPage, RazorPage<T>) properties (UrlEncoder,MetadataProvider)
- A couple of configuration properties (Html5DateRenderingMode, IdAttributeDotReplacement)
We will look into these methods in more detail in Chapter 13, Understanding How Testing Works. For now, let's see how we can add our own extension (helper) methods. The easiest way is to add an extension method over IHtmlHelper<T>, as illustrated in the following code snippet:
public static HtmlString CurrentUser(this IHtmlHelper<T> html)
{
return new HtmlString(html.ViewContext.HttpContext.
User.Identity.Name);
}
Now, you can use it in every view, like this:
@Html.CurrentUser()
Make sure that you either return string or IHtmlContent from it; otherwise, you won't be able to use this syntax.
We've seen that the ViewResult class offers the following three properties that can be used to pass data from an action into a view:
- The model (Model): In the early days of ASP.NET MVC, this was the only mechanism that could be used; we needed to define a possibly quite complex class with all the data that we would like to make available.
- The view data (ViewData): Now that we have a strongly typed collection of random values, this has gained in popularity against the model.
- The temporary data (TempData): Data that will only be available until the next request.
These properties are eventually passed along to identically named ones in the RazorPage<T> class.
It is even possible, but not too common, to specify the view engine (an instance of IViewEngine) that should be used by the view rendering process, by setting a value to the ViewEngine property. Normally, this is looked after automatically.
- 密碼學原理與Java實現
- 信息可視化的藝術:信息可視化在英國
- HTML5 Mobile Development Cookbook
- 深入淺出Android Jetpack
- Koa開發:入門、進階與實戰
- Python王者歸來
- Visual Basic程序設計實踐教程
- 蘋果的產品設計之道:創建優秀產品、服務和用戶體驗的七個原則
- ExtJS Web應用程序開發指南第2版
- Java Web應用開發項目教程
- Fastdata Processing with Spark
- 每個人的Python:數學、算法和游戲編程訓練營
- Hands-On ROS for Robotics Programming
- Learning Apache Thrift
- PHP程序設計經典300例