- 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.
- Oracle從入門到精通(第3版)
- jQuery Mobile Web Development Essentials(Third Edition)
- 大學(xué)計(jì)算機(jī)基礎(chǔ)實(shí)驗(yàn)教程
- Rust編程從入門到實(shí)戰(zhàn)
- Getting Started with CreateJS
- Mastering AndEngine Game Development
- PhpStorm Cookbook
- UML 基礎(chǔ)與 Rose 建模案例(第3版)
- C語言從入門到精通
- Practical Game Design with Unity and Playmaker
- 單片機(jī)原理及應(yīng)用技術(shù)
- ASP.NET求職寶典
- ROS機(jī)器人編程實(shí)戰(zhàn)
- Python編程入門(第3版)
- Flask開發(fā)Web搜索引擎入門與實(shí)戰(zhàn)