/// <summary> /// Starts a new writing scope and optionally overrides <see cref="HtmlEncoder"/> within that scope. /// </summary> /// <param name="encoder"> /// The <see cref="System.Text.Encodings.Web.HtmlEncoder"/> to use when this <see cref="RazorPage"/> handles /// non-<see cref="IHtmlContent"/> C# expressions. If <c>null</c>, does not change <see cref="HtmlEncoder"/>. /// </param> /// <remarks> /// All writes to the <see cref="Output"/> or <see cref="ViewContext.Writer"/> after calling this method will /// be buffered until <see cref="EndTagHelperWritingScope"/> is called. /// </remarks> public void StartTagHelperWritingScope(HtmlEncoder encoder) { var buffer = new ViewBuffer(BufferScope, Key, ViewBuffer.TagHelperPageSize); TagHelperScopes.Push(new TagHelperScopeInfo(buffer, HtmlEncoder, PageContext.Writer)); // If passed an HtmlEncoder, override the property. if (encoder != null) { HtmlEncoder = encoder; } // We need to replace the ViewContext's Writer to ensure that all content (including content written // from HTML helpers) is redirected. PageContext.Writer = new ViewBufferTextWriter(buffer, PageContext.Writer.Encoding); }
/// <summary> /// Ends the current writing scope that was started by calling <see cref="StartTagHelperWritingScope"/>. /// </summary> /// <returns>The buffered <see cref="TagHelperContent"/>.</returns> public TagHelperContent EndTagHelperWritingScope() { if (TagHelperScopes.Count == 0) { throw new InvalidOperationException("There is no active scope to write"); } var scopeInfo = TagHelperScopes.Pop(); // Get the content written during the current scope. var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.AppendHtml(scopeInfo.Buffer); // Restore previous scope. HtmlEncoder = scopeInfo.HtmlEncoder; PageContext.Writer = scopeInfo.Writer; return(tagHelperContent); }
/// <summary> /// Ends the current writing scope that was started by calling <see cref="StartTagHelperWritingScope"/>. /// </summary> /// <returns>The buffered <see cref="TagHelperContent"/>.</returns> public TagHelperContent EndTagHelperWritingScope() { if (TagHelperScopes.Count == 0) { throw new InvalidOperationException(Resources.RazorPage_ThereIsNoActiveWritingScopeToEnd); } var scopeInfo = TagHelperScopes.Pop(); // Get the content written during the current scope. var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.AppendHtml(scopeInfo.Buffer); // Restore previous scope. HtmlEncoder = scopeInfo.HtmlEncoder; ViewContext.Writer = scopeInfo.Writer; return(tagHelperContent); }