官术网_书友最值得收藏!

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.

Do not forget that the precompilation only occurs at publish, not build, time!

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.

主站蜘蛛池模板: 武义县| 福安市| 镇巴县| 宜城市| 彭山县| 天气| 大连市| 胶南市| 武穴市| 荆门市| 伊金霍洛旗| 邛崃市| 盐边县| 通州区| 夏河县| 栾川县| 龙山县| 临朐县| 米林县| 肇源县| 宿州市| 武汉市| 仁布县| 乌兰察布市| 永川市| 麻栗坡县| 朝阳市| 龙门县| 平远县| 柘荣县| 沧源| 桐城市| 方山县| 丰县| 昭觉县| 余江县| 若尔盖县| 洪江市| 本溪| 牡丹江市| 华容县|