### RazorSlices .csproj Configuration Example
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
A complete .csproj file example showing how to enable RazorSlices and configure related options like trimming and proxy generation.
```xml
net8.0enableenabletruepartialtruefalse
```
--------------------------------
### Generated Proxy Class Example
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Example of a generated proxy class for a Razor Slice, demonstrating type-safe Create() methods in the global namespace.
```csharp
// Generated in global namespace
public sealed partial class HomePage : IRazorSliceProxy
{
public static RazorSlice CreateSlice()
{
var instance = new HomePage();
instance.Initialize = (slice, sp, hc) => { /* ... */ };
return instance;
}
}
```
--------------------------------
### Usage of IRazorSliceProxy.CreateSlice()
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Example demonstrating how to use the CreateSlice() method to instantiate and render a RazorSlice without a model.
```csharp
// For a slice named MySlice.cshtml
var slice = Slices.MySlice.CreateSlice();
await slice.RenderAsync(writer);
```
--------------------------------
### RazorSlice Include/Exclude Examples
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Demonstrates various ways to use `RazorSlice` include and exclude attributes with glob patterns to define which files are processed as Razor Slices.
```xml
```
```xml
```
```xml
```
--------------------------------
### RenderSectionAsync Example
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Shows how to use `RenderSectionAsync` to render specific sections like 'head' or 'scripts' within a layout. Child slices must override `ExecuteSectionAsync` to provide content for these named sections.
```cshtml
@inherits RazorLayoutSlice
```
--------------------------------
### Implementing IUsesLayout in a Razor Slice
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Example of implementing the IUsesLayout interface in a .cshtml file to apply a layout with a specific model.
```cshtml
@inherits RazorSlice
@implements IUsesLayout<_Layout, LayoutModel>
@Model.Title
@Model.Content
@functions {
public LayoutModel LayoutModel => new()
{
SiteTitle = "My Blog",
Version = "1.0"
};
}
```
--------------------------------
### Templated Razor Delegate Example
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Illustrates the use of a templated Razor delegate, which is a delegate that can render Razor markup. This example shows how to define and invoke a delegate that accepts an item and renders it within a div.
```cshtml
@inherits RazorSlice
@{
var tmpl = @
This is a templated Razor delegate. The following value was passed in: @item
;
}
@tmpl(DateTime.Now)
```
--------------------------------
### Return RazorSlices from Minimal APIs (Direct)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Example of directly returning a RazorSlice instance from a Minimal API endpoint.
```csharp
app.MapGet("/", () => Slices.Home.Create());
```
--------------------------------
### Render RazorSlice to Stream
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Example of rendering a RazorSlice directly to a stream, such as a MemoryStream.
```csharp
var slice = MySlice.Create();
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
await slice.RenderAsync(writer);
```
--------------------------------
### RenderBodyAsync Example
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Demonstrates how to use `RenderBodyAsync` within a layout's `.cshtml` file to inject the child slice's body content. This is typically placed in the main content area of the layout.
```cshtml
@inherits RazorLayoutSlice
My Site
Welcome
@await RenderBodyAsync()
```
--------------------------------
### HttpContext Property
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Gets or sets the HttpContext associated with the current request.
```csharp
public HttpContext? HttpContext { get; set; }
```
--------------------------------
### Simple Route Handler with RazorSlice
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/iresult-extensions.md
Use Results.RazorSlice to render a RazorSlice component for a simple GET request.
```csharp
app.MapGet("/hello", () =>
{
return Results.RazorSlice();
});
```
--------------------------------
### ContentType Property
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Gets or sets the HTTP response content type. Defaults to 'text/html; charset=utf-8'.
```csharp
public string ContentType { get; set; }
```
--------------------------------
### HtmlEncoder Property
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Gets or sets the HtmlEncoder used for rendering. Defaults to HtmlEncoder.Default if null.
```csharp
public HtmlEncoder? HtmlEncoder { get; set; }
```
--------------------------------
### Map Minimal API to Render Razor Slice
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Integrate Razor Slices into your ASP.NET Core application by mapping a minimal API endpoint to render a Razor Slice. This example shows how to use the generated `Create` method.
```csharp
app.MapGet("/hello", () => MyApp.Slices.Hello.Create(DateTime.Now));
```
--------------------------------
### Add RazorSlices NuGet Package
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Install the RazorSlices NuGet package using the .NET CLI. This is the first step to using Razor Slices in your ASP.NET Core project.
```shell
> dotnet add package RazorSlices
```
--------------------------------
### Usage in a Razor Template
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-generic.md
Example of how to use the strongly-typed Model property within a .cshtml file. Ensure the @inherits directive matches the expected TModel type.
```cshtml
@inherits RazorSlice
@Model.Title
Due: @Model.DueDate
Complete: @(Model.IsComplete ? "Yes" : "No")
```
--------------------------------
### ServiceProvider Property
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Gets or sets the IServiceProvider for resolving services. It's lazily initialized from HttpContext.RequestServices if not set.
```csharp
public IServiceProvider? ServiceProvider { get; set; }
```
--------------------------------
### Templated Razor Method Example
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Demonstrates a templated Razor method that accepts a model and renders HTML content. The method is defined within the @functions block and can be invoked directly in the Razor view.
```cshtml
@inherits RazorSlice
@Title(Model)
@functions {
private IHtmlContent Title(Todo todo)
{
Todo @todo.Id: @todo.Title
return HtmlString.Empty;
}
}
```
--------------------------------
### Render Generic Attribute Value
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/html-attributes.md
Examples of rendering generic attribute values in Razor. These demonstrate setting attributes like 'id', 'href', and 'alt' with dynamic values.
```cshtml
```
```cshtml
Link
```
```cshtml
```
--------------------------------
### Add RazorSlices NuGet Package (Console)
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Install the RazorSlices NuGet package using the .NET CLI in a console environment. This is a common way to add dependencies to .NET projects.
```console
> dotnet add package RazorSlices
```
--------------------------------
### Using Razor Slice in Minimal API
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-generic.md
Example of how to use a generated Razor Slice in a minimal API endpoint. It creates a Todo object and returns the result of calling the generated Create method on the slice.
```csharp
app.MapGet("/todos/{id}", (int id) =>
{
var todo = new Todo
{
Id = id,
Title = "Buy groceries",
DueDate = DateTime.Now.AddDays(1),
IsComplete = false
};
return Slices.TodoItem.Create(todo);
});
```
--------------------------------
### Configure Razor Slices Source Generator Inclusion
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Customize which .cshtml files are processed by the Razor Slices source generator. This example shows how to include only files within the 'Slices' directory and exclude specific layout/import files.
```xml
false
```
--------------------------------
### RazorSlice Nested Slices
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Render nested RazorSlices to build complex UI structures. This example shows how to render a list of order items within an order details view, using RenderPartialAsync to render each item.
```cshtml
@inherits RazorSlice
Order #@Model.Id
@foreach (var item in Model.Items)
{
@(await RenderPartialAsync(item))
}
```
--------------------------------
### Build and Test Solution
Source: https://github.com/damianedwards/razorslices/blob/main/AGENTS.md
Commands to build the entire solution, run all tests, or execute specific test projects. Also includes how to run the sample web application.
```shell
# Build entire solution
dotnet build
# Run all tests
dotnet test
# Run specific test project
dotnet test tests/SourceGenerator
dotnet test tests/Samples.WebApp
# Run the sample web app
dotnet run --project samples/WebApp
```
--------------------------------
### Configure GitHub Packages Source for Pre-release Builds
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Set up nuget.config to use GitHub Packages for pre-release builds, including authentication with a personal access token.
```xml
```
--------------------------------
### Configure .NET SDK Version with global.json
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Specify the .NET SDK version and roll-forward policy for your project using a global.json file.
```json
{
"sdk": {
"version": "8.0.0",
"rollForward": "latestFeature"
}
}
```
--------------------------------
### Usage of IRazorSliceProxy.CreateSlice() and Shorthand
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Demonstrates creating a RazorSlice instance with a model using both the explicit CreateSlice() method and the shorthand Create() method provided by the source generator.
```csharp
var todo = new Todo { Title = "Buy milk", DueDate = DateTime.Now };
var slice = Slices.TodoItem.CreateSlice(todo);
// or use the shorthand:
var slice = Slices.TodoItem.Create(todo);
```
--------------------------------
### StatusCode Property
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Gets or sets the HTTP status code for the response. Defaults to 200 (OK).
```csharp
public int StatusCode { get; set; }
```
--------------------------------
### Creating a RazorSlice Instance with a Model
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-generic.md
Demonstrates how to create an instance of a RazorSlice with a specific model using the generated proxy's Create method.
```csharp
var todo = new Todo { Title = "Buy milk", DueDate = DateTime.Now };
var slice = Slices.TodoItem.Create(todo);
```
--------------------------------
### Usage in Minimal API
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Demonstrates how to integrate a Razor Slice into a minimal API endpoint. It shows fetching product data and creating a product slice to be returned.
```csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/products/{id}", (int id) =>
{
var product = GetProductById(id); // Your data access
return Slices.Product.Create(product);
});
app.Run();
```
--------------------------------
### Add GitHub Packages Feed for CI Builds
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Configure your NuGet client to use the GitHub Packages feed for CI builds. This requires a personal access token with the `read:packages` scope.
```shell
~> dotnet nuget add source -n GitHub -u -p https://nuget.pkg.github.com/DamianEdwards/index.json
```
--------------------------------
### Render RazorSlices Partials
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Demonstrates how to render partial RazorSlices by instance, type, or with a model.
```cshtml
@await RenderPartialAsync(MyPartial.Create())
@(await RenderPartialAsync())
@(await RenderPartialAsync(todoItem))
```
--------------------------------
### Render Conditional Boolean Attribute
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/html-attributes.md
Example of rendering a boolean attribute conditionally in Razor. The attribute is included only when the condition is true.
```cshtml
```
```cshtml
```
--------------------------------
### Display Error Page
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Render a custom error page with a specific status code. This example shows how to create an `ErrorViewModel` and pass it to the `ErrorPage` RazorSlice.
```csharp
app.MapGet("/error/{code}", (int code) =>
{
var errorModel = new ErrorViewModel { StatusCode = code };
return Results.RazorSlice(errorModel);
});
```
--------------------------------
### Route Handler with Model and RazorSlice
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/iresult-extensions.md
Pass a model to RazorSlice for rendering dynamic content in a GET request. Handles cases where the model might not be found.
```csharp
app.MapGet("/user/{id}", (int id) =>
{
var user = userRepository.GetById(id);
if (user == null)
{
return Results.NotFound();
}
return Results.RazorSlice(user);
});
```
--------------------------------
### Content Model (Product.cs)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Defines the data model for a product, including its name, description, and price. This model is used by the content slice.
```csharp
namespace MyApp;
public class Product
{
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
}
```
--------------------------------
### Configure Official NuGet Package Source
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Add the official NuGet package source to your nuget.config file.
```xml
```
--------------------------------
### Conditional Rendering in Razor Slices
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Conditionally render HTML elements based on a model property. This example shows how to display an admin link only if the user is an administrator.
```cshtml
@if (Model.IsAdmin)
{
Admin
}
```
--------------------------------
### Add RazorSlices Package from GitHub Source
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Use the .NET CLI to add the RazorSlices package, specifying the GitHub package source.
```bash
dotnet add package RazorSlices --source github
```
--------------------------------
### Partials and Composition Methods
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Methods for rendering partial slices and composing output.
```APIDOC
## RenderPartialAsync(RazorSlice)
### Description
Renders another `RazorSlice` instance as a partial view.
### Method
`RenderPartialAsync`
### Parameters
- `RazorSlice` - The partial slice to render.
### Source
`RazorSlice`
```
```APIDOC
## RenderPartialAsync()
### Description
Renders a partial slice by its type.
### Method
`RenderPartialAsync`
### Parameters
- `TSlice` - The type of the partial slice to render.
### Source
`RazorSlice`
```
```APIDOC
## RenderPartialAsync(model)
### Description
Renders a partial slice of a specific type with a provided model.
### Method
`RenderPartialAsync`
### Parameters
- `TSlice` - The type of the partial slice.
- `TModel` - The type of the model.
- `model` - The model instance to pass to the partial slice.
### Source
`RazorSlice`
```
```APIDOC
## FlushAsync()
### Description
Flushes any buffered output to the underlying writer.
### Method
`FlushAsync`
### Source
`RazorSlice`
```
--------------------------------
### Recommended RazorSlices Project Structure
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Illustrates a typical directory layout for a RazorSlices project, separating slices, models, services, and the main program file.
```text
MyProject/
├── Slices/
│ ├── _ViewImports.cshtml
│ ├── HomePage.cshtml
│ ├── Shared/
│ │ ├── _Layout.cshtml
│ │ ├── _Header.cshtml
│ │ └── _Footer.cshtml
│ ├── Products/
│ │ ├── _ViewImports.cshtml (optional, product-specific imports)
│ │ ├── List.cshtml
│ │ └── Detail.cshtml
│ └── Admin/
│ ├── Dashboard.cshtml
│ └── Users.cshtml
├── Models/
│ ├── Product.cs
│ ├── User.cs
│ └── ...
├── Services/
│ └── ...
└── Program.cs
```
--------------------------------
### Render a Simple Page with Razor Slices
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Use this to render a basic page. Ensure Razor Slices is configured in your application.
```csharp
app.MapGet("/", () => Slices.HomePage.Create());
```
--------------------------------
### RazorSlice Conditional Content
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Render content conditionally based on user roles or other criteria. This example demonstrates how to display an 'Admin Panel' link only if the current user is an administrator.
```cshtml
@{
var isAdmin = User?.IsAdmin ?? false;
}
@if (isAdmin)
{
Admin Panel
}
```
--------------------------------
### Set Slice Content Type
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Set the Content-Type header for a Razor Slice response. This allows you to specify the MIME type and character encoding of the response, for example, 'application/xhtml+xml; charset=utf-8'.
```csharp
var slice = MySlice.Create();
slice.ContentType = "application/xhtml+xml; charset=utf-8";
return slice;
```
--------------------------------
### Implementing IUsesLayout in a .cshtml file
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Implement this interface in a .cshtml file to apply a layout to the current slice. The layout's RenderBodyAsync() method will render the content of this slice.
```cshtml
@inherits RazorSlice
@implements IUsesLayout<_Layout>
My Page
Content goes here
```
--------------------------------
### Render a Page with Model Data using Razor Slices
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Render a page that displays user-specific data. This requires a repository to fetch the user and a Razor Slice component that accepts a model.
```csharp
app.MapGet("/user/{id}", (int id) =>
{
var user = repository.GetUser(id);
return Slices.UserProfile.Create(user);
});
```
--------------------------------
### Create Slices Directory Structure
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Organize your Razor Slices within a dedicated 'Slices' directory, including a _ViewImports.cshtml file.
```text
Slices/
├── _ViewImports.cshtml
└── HomePage.cshtml
```
--------------------------------
### Configure .csproj for Slice Detection
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Configure your .csproj file to explicitly define which .cshtml files are treated as Razor Slices. This allows for fine-grained control over slice detection, disabling the default behavior and specifying include/exclude patterns.
```xml
false
```
--------------------------------
### Custom Section Rendering in Layout
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Demonstrates how to override ExecuteSectionAsync in a layout slice to render custom HTML content for specific sections. This allows for dynamic content injection into predefined layout areas.
```csharp
protected override Task ExecuteSectionAsync(string name)
{
if (name == "lorem-header")
{
This page renders a custom IHtmlContent type that contains lorem ipsum content.
}
return Task.CompletedTask;
}
```
--------------------------------
### Compiler-Generated Code for Conditional Class Attribute
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/html-attributes.md
Example of how the Razor compiler generates calls to `BeginWriteAttribute`, `WriteAttributeValue`, and `EndWriteAttribute` for a Razor component with a conditional class attribute. This demonstrates handling dynamic values and conditional rendering.
```cshtml
```
```csharp
BeginWriteAttribute("class", " class=\"", offset1, "\"", offset2, 2);
WriteAttributeValue("", 0, "form-control ", literalOffset, 13, true);
WriteAttributeValue(" ", 0, isRequired ? "required" : "", valueOffset, 8, false);
EndWriteAttribute();
```
--------------------------------
### Basic Razor Slice Usage
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/README.md
Demonstrates how to define a basic Razor Slice component with a strongly-typed model. This is useful for rendering product information.
```cshtml
@inherits RazorSlice
@Model.Name
Price: @WriteNumber(Model.Price, "C")
In Stock: @WriteBool(Model.InStock)
```
--------------------------------
### Configure _ViewImports.cshtml for Razor Slices
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Set up the _ViewImports.cshtml file to inherit from RazorSlice and import necessary namespaces.
```cshtml
@inherits RazorSlice
@using RazorSlices
```
--------------------------------
### Handle Not Found Response
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Return a 404 Not Found result when a requested resource is not found. This snippet demonstrates how to check for a null user and return `Results.NotFound()`.
```csharp
app.MapGet("/user/{id}", (int id) =>
{
var user = GetUser(id);
if (user == null)
return Results.NotFound();
return Results.RazorSlice(user);
});
```
--------------------------------
### Create and Render Razor Slice by Proxy Type (No Model)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/iresult-extensions.md
Creates and renders a slice of the specified proxy type without a model. More efficient than creating a slice instance first if you don't need to configure it beforehand.
```csharp
app.MapGet("/", () => Results.RazorSlice());
app.MapDelete("/", () =>
Results.RazorSlice(StatusCodes.Status204NoContent));
```
--------------------------------
### RenderAsync (PipeWriter Overload)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Renders the template to a `PipeWriter` for high-performance streaming. This is useful for scenarios where you need to stream the output directly to a network response or other asynchronous sinks.
```APIDOC
## RenderAsync (PipeWriter Overload)
### Description
Renders the template to a `PipeWriter` for high-performance streaming.
### Method
`RenderAsync`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **pipeWriter** (`PipeWriter`) - Required - The pipe writer to render to.
- **htmlEncoder** (`HtmlEncoder?`) - Optional - Custom HTML encoder; defaults to `HtmlEncoder.Default`.
- **cancellationToken** (`CancellationToken`) - Optional - Cancellation token for the operation.
### Return Type
`ValueTask` — completes when rendering finishes
### Throws
`ArgumentNullException` if `pipeWriter` is `null`
### Example
```csharp
var slice = MySlice.Create();
using var pipe = PipeWriter.Create(outputStream);
await slice.RenderAsync(pipe);
await pipe.FlushAsync();
```
```
--------------------------------
### Render RazorSlice to PipeWriter
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Shows how to render a RazorSlice to a PipeWriter, commonly used for network streams.
```csharp
var slice = MySlice.Create();
var pipe = PipeWriter.Create(networkStream);
await slice.RenderAsync(pipe);
```
--------------------------------
### Layout Rendering Methods
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Methods for rendering content within a layout structure.
```APIDOC
## RenderBodyAsync()
### Description
Renders the main content body within a layout.
### Method
`RenderBodyAsync`
### Source
`RazorLayoutSlice`
```
```APIDOC
## RenderSectionAsync(name)
### Description
Renders a named section within a layout.
### Method
`RenderSectionAsync`
### Parameters
- `name` - The name of the section to render.
### Source
`RazorLayoutSlice`
```
```APIDOC
## ExecuteSectionAsync(name)
### Description
Provides the content for a named section. This is typically used within a `RazorSlice` to define content for a section that a layout will render.
### Method
`ExecuteSectionAsync`
### Parameters
- `name` - The name of the section.
### Source
`RazorSlice`
```
--------------------------------
### Generated Create Method Signature
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-generic.md
Illustrates the signature of the strongly-typed Create method generated by the source generator for a specific model type.
```csharp
// For @inherits RazorSlice:
abstract static RazorSlice Create(Todo model);
```
--------------------------------
### Render RazorSlice to String
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Demonstrates rendering a RazorSlice to a string using a StringBuilder and StringWriter.
```csharp
var slice = MySlice.Create();
var sb = new StringBuilder();
var writer = new StringWriter(sb);
await slice.RenderAsync(writer);
var html = sb.ToString();
```
--------------------------------
### Project File Settings for Razor Slice Proxies
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-generic.md
Control proxy generation in your .csproj file. You can configure proxies to be generated as records and explicitly enable or disable default slice detection. If default detection is disabled, you must specify which files to treat as slices.
```xml
truefalse
```
--------------------------------
### Format Dates and Numbers
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Utilize `WriteDate` and `WriteNumber` helpers for formatted output. These methods accept format strings and culture information for precise control over display.
```cshtml
@WriteDate(Model.CreatedAt, "yyyy-MM-dd")
@WriteNumber(Model.Price, "C")
@WriteNumber(Model.Value, "N2", CultureInfo.InvariantCulture)
```
--------------------------------
### Main Layout (_Layout.cshtml)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Defines the overall HTML structure for the application, including header, navigation, main content area, and footer. It utilizes Razor Sections for head and script injection.
```cshtml
@inherits RazorLayoutSlice@Model.Title
@await RenderSectionAsync("head")
@await RenderBodyAsync()
@await RenderSectionAsync("scripts")
@functions {
// Layout model definition
}
```
--------------------------------
### Create a Basic Razor Slice with a Model
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Define a Razor Slice file (e.g., Hello.cshtml) with a model type. The source generator will create a strongly-typed `Create` method based on the model specified in the `@inherits` directive.
```cshtml
@inherits RazorSliceHello from Razor Slices!
Hello from Razor Slices! The time is @Model
```
--------------------------------
### IUsesLayout Interface Definition
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Marks a slice to use another slice as its layout. The layout must inherit from IRazorSliceProxy. This interface is implemented in a slice's .cshtml file to apply a layout.
```csharp
public interface IUsesLayout
where TLayout : IRazorSliceProxy
{
public RazorSlice CreateLayout() => TLayout.CreateSlice();
RazorSlice IUsesLayout.CreateLayoutImpl() => CreateLayout();
}
```
--------------------------------
### Rendering Methods
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Methods for rendering Razor slices to different output targets.
```APIDOC
## RenderAsync(PipeWriter, ...)
### Description
Renders the Razor slice content directly to a `PipeWriter`.
### Method
`RenderAsync`
### Parameters
- `PipeWriter` - The target pipe writer.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## RenderAsync(TextWriter, ...)
### Description
Renders the Razor slice content to a `TextWriter`.
### Method
`RenderAsync`
### Parameters
- `TextWriter` - The target text writer.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## ExecuteAsync()
### Description
Executes the Razor slice template. This is an abstract method and typically overridden by concrete implementations.
### Method
`ExecuteAsync`
### Source
`RazorSlice`
```
--------------------------------
### Apply Dynamic Attributes in HTML
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Shows how to conditionally apply boolean attributes, classes, and multiple dynamic attributes to HTML elements.
```cshtml
Click
```
--------------------------------
### Create Basic Razor Slice
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Use this to create a simple Razor Slice without a model. It's useful for static content or pages where data is fetched within the slice itself.
```cshtml
@inherits RazorSlice
Welcome
```
```csharp
app.MapGet("/", () => Slices.HomePage.Create());
```
--------------------------------
### Recommended _ViewImports.cshtml Content
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
This Razor syntax provides recommended shared imports for all Razor Slices within a directory and its subdirectories. It includes base class inheritance, common namespaces, and disabling tag helpers that require MVC.
```cshtml
@inherits RazorSlice
@using System.Globalization
@using Microsoft.AspNetCore.Razor
@using Microsoft.AspNetCore.Http.HttpResults
@using RazorSlices
@using YourApp.Models
@using YourApp.Services
@* Disable tag helpers that require MVC *@
@tagHelperPrefix __disable_tagHelpers__:
@removeTagHelper *, Microsoft.AspNetCore.Mvc.Razor
```
--------------------------------
### RenderAsync (TextWriter Overload)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Renders the template to a `TextWriter`. This method is suitable for scenarios where you are working with synchronous writers or need to integrate with existing text-based output mechanisms.
```APIDOC
## RenderAsync (TextWriter Overload)
### Description
Renders the template to a `TextWriter`.
### Method
`RenderAsync`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **textWriter** (`TextWriter`) - Required - The text writer to render to.
- **htmlEncoder** (`HtmlEncoder?`) - Optional - Custom HTML encoder; defaults to `HtmlEncoder.Default`.
- **cancellationToken** (`CancellationToken`) - Optional - Cancellation token for the operation.
### Return Type
`ValueTask` — completes when rendering finishes
### Throws
`ArgumentNullException` if `textWriter` is `null`
### Example
```csharp
var slice = MySlice.Create();
using var writer = new StreamWriter(outputStream);
await slice.RenderAsync(writer);
await writer.FlushAsync();
```
```
--------------------------------
### Render Raw HTML
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Use `Html.Raw()` or `WriteHtml()` to render pre-encoded HTML content without further encoding. Use this cautiously when dealing with trusted HTML sources.
```cshtml
@Html.Raw(Model.HtmlContent)
@WriteHtml(preEncodedContent)
```
--------------------------------
### Create Razor Slice with Model
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Create a Razor Slice that accepts a model for dynamic content rendering. Ensure the model type is correctly specified in the `@inherits` directive.
```cshtml
@inherits RazorSlice
@Model.Name
@Model.Description
```
```csharp
app.MapGet("/products/{id}", (int id) =>
{
var product = GetProduct(id);
return Slices.ProductPage.Create(product);
});
```
--------------------------------
### Add RazorSlices Package via CLI
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Use the .NET CLI to add the RazorSlices NuGet package to your project.
```bash
dotnet add package RazorSlices
```
--------------------------------
### Content Slice (Pages/Product.cshtml)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Represents a specific content component for a product page. It implements the layout interface and defines how to render product details and inject content into layout sections.
```cshtml
@inherits RazorSlice
@implements IUsesLayout<_Layout, LayoutModel>
@Model.Name
@Model.Description
$@Model.Price:N2
@functions {
public LayoutModel LayoutModel => new()
{
Title = $"{Model.Name} - My Store",
CompanyName = "Acme Inc."
};
protected override Task ExecuteSectionAsync(string sectionName)
{
if (sectionName == "head")
{
}
if (sectionName == "scripts")
{
}
return Task.CompletedTask;
}
}
```
--------------------------------
### RazorSlices Configuration
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/README.md
Configuration options for enabling and customizing RazorSlices behavior.
```APIDOC
## RazorSlices Configuration
### Description
Options for configuring the RazorSlices library, including automatic detection of slice files, explicit inclusion, and the use of record types for proxies.
### Configuration Options
- `EnableDefaultRazorSlices`: Enables automatic detection and inclusion of `.cshtml` files as RazorSlices.
- `RazorSlice`: Allows for explicit inclusion of specific RazorSlice files.
- `RazorSliceProxiesAsRecords`: Configures the use of record types for RazorSlice proxies.
```
--------------------------------
### Define a Razor Layout Slice
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
This snippet demonstrates how to create a layout slice using RazorLayoutSlice. Layouts provide common page structure and use RenderBodyAsync to inject content.
```cshtml
@inherits RazorLayoutSlice
@await RenderBodyAsync()
```
--------------------------------
### Layout Model (LayoutModel.cs)
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Defines the data model used by the main layout. It includes properties for the page title and company name.
```csharp
namespace MyApp;
public class LayoutModel
{
public string Title { get; set; } = "My App";
public string CompanyName { get; set; } = "Acme Inc.";
}
```
--------------------------------
### Create a Basic Razor Slice
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Define a simple Razor Slice component that renders an H1 tag.
```cshtml
@inherits RazorSlice
Hello from Razor Slices
```
--------------------------------
### HTML Attribute Methods
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Methods for programmatically writing HTML attributes.
```APIDOC
## BeginWriteAttribute(...)
### Description
Starts the process of writing an HTML attribute.
### Method
`BeginWriteAttribute`
### Parameters
- `...` - Arguments defining the attribute (e.g., name, type).
### Source
`RazorSlice`
```
```APIDOC
## WriteAttributeValue(...)
### Description
Writes a value for an HTML attribute.
### Method
`WriteAttributeValue`
### Parameters
- `T` - The type of the value.
- `...` - Arguments defining the value.
### Source
`RazorSlice`
```
```APIDOC
## EndWriteAttribute()
### Description
Completes the writing of an HTML attribute.
### Method
`EndWriteAttribute`
### Source
`RazorSlice`
```
--------------------------------
### RazorLayoutSlice Layout Rendering
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/README.md
Methods for rendering content within layout templates.
```APIDOC
## RazorLayoutSlice Layout Rendering
### Description
Methods used within layout templates to render the main content body, named sections, and provide content for sections.
### Methods
- `RenderBodyAsync()`: Render the main content body within the layout.
- `RenderSectionAsync()`: Render a named section defined in the layout.
- `ExecuteSectionAsync()`: Provide content for a named section.
```
--------------------------------
### FlushAsync
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Attempts to flush the underlying output the template is being rendered to. This method is useful for ensuring that content is sent to the client immediately.
```APIDOC
## FlushAsync
### Description
Attempts to flush the underlying output the template is being rendered to.
### Method
`ValueTask FlushAsync()`
### Returns
`ValueTask` — completes when flush finishes
### Example
```cshtml
@await FlushAsync()
```
```
--------------------------------
### IUsesLayout Interface Implementation
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/layouts.md
Declares that a slice uses another slice with a model as its layout. This version supports passing a model to the layout slice.
```cshtml
@inherits RazorSlice
@implements IUsesLayout<_Layout, LayoutModel>
@Model.Title
@Model.Content
@functions {
public LayoutModel LayoutModel => new()
{
Title = "My Site",
Version = "1.0"
};
}
```
--------------------------------
### Create Razor Layout Slice
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Define a layout slice by inheriting from `RazorLayoutSlice`. This serves as a template for other slices, defining the overall page structure.
```cshtml
@inherits RazorLayoutSlice
My Site
@await RenderSectionAsync("head")
@await RenderBodyAsync()
@await RenderSectionAsync("scripts")
```
--------------------------------
### IUsesLayout Interface Definition
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Defines the IUsesLayout interface, which requires a LayoutModel property and provides a CreateLayout method for creating layout slices.
```csharp
public interface IUsesLayout : IUsesLayout
where TLayout : IRazorSliceProxy
{
TLayoutModel LayoutModel { get; }
public RazorSlice CreateLayout() => TLayout.CreateSlice(LayoutModel);
RazorSlice IUsesLayout.CreateLayoutImpl() => CreateLayout();
}
```
--------------------------------
### Render Razor Slice to PipeWriter
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Use this method for high-performance streaming of Razor Slice output to a PipeWriter. Ensure the PipeWriter is properly created and flushed.
```csharp
public ValueTask RenderAsync(
PipeWriter pipeWriter,
HtmlEncoder? htmlEncoder = null,
CancellationToken cancellationToken = default)
```
```csharp
var slice = MySlice.Create();
using var pipe = PipeWriter.Create(outputStream);
await slice.RenderAsync(pipe);
await pipe.FlushAsync();
```
--------------------------------
### Configure _ViewImports.cshtml for Razor Slices
Source: https://github.com/damianedwards/razorslices/blob/main/README.md
Set up the _ViewImports.cshtml file in your Slices directory to inherit from RazorSlice and configure tag helpers. This file is essential for all your Razor Slice files.
```cshtml
@inherits RazorSlice
@using System.Globalization;
@using Microsoft.AspNetCore.Razor;
@using Microsoft.AspNetCore.Http.HttpResults;
@using RazorSlices;
@tagHelperPrefix __disable_tagHelpers__:
@removeTagHelper *, Microsoft.AspNetCore.Mvc.Razor
```
--------------------------------
### IUsesLayout
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Marks a slice as using a layout that accepts a model. The layout must inherit from RazorLayoutSlice. Use this interface when the layout requires its own model.
```APIDOC
## Interface IUsesLayout
### Description
Marks a slice as using a layout that accepts a model. The layout must inherit from `RazorLayoutSlice`. Use this interface when the layout requires its own model.
### Type Parameters
| Parameter | Constraint | Description |
|-----------|-----------|-------------|
| `TLayout` | `IRazorSliceProxy` | Layout slice proxy type accepting a model |
| `TLayoutModel` | — | The layout model type |
### Members
#### LayoutModel Property
```csharp
TLayoutModel LayoutModel { get; }
```
Gets the layout model to pass to the layout slice. Implement this property to provide the model.
| Aspect | Details |
|--------|---------|
| **Type** | `TLayoutModel` |
| **Access** | Public get |
| **Implementation** | Required |
### Usage Example
```cshtml
@inherits RazorSlice
@implements IUsesLayout<_Layout, LayoutModel>
@Model.Title
@Model.Content
@functions {
public LayoutModel LayoutModel => new() {
SiteTitle = "My Blog",
Version = "1.0"
};
}
```
When rendered, the layout receives the model returned by the `LayoutModel` property.
```
--------------------------------
### LayoutModel Property Definition
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/interfaces.md
Specifies the signature for the LayoutModel property, which must be implemented to provide the model for the layout slice.
```csharp
TLayoutModel LayoutModel { get; }
```
--------------------------------
### Formatting and Value Writing Methods
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/INDEX.md
Methods for writing formatted primitive types and other formattable objects.
```APIDOC
## WriteSpanFormattable(T, format, ...)
### Description
Writes an object implementing `ISpanFormattable` with a specified format.
### Method
`WriteSpanFormattable`
### Parameters
- `T` - The formattable object.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## WriteUtf8SpanFormattable(T, format, ...)
### Description
Writes an object implementing `IUtf8SpanFormattable` with a specified format.
### Method
`WriteUtf8SpanFormattable`
### Parameters
- `T` - The formattable object.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## WriteDate(DateTime?, format, ...)
### Description
Writes a nullable `DateTime` value, formatted according to the provided format string.
### Method
`WriteDate`
### Parameters
- `DateTime?` - The nullable date and time value.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## WriteNumber(int?, format, ...)
### Description
Writes a nullable integer value, formatted according to the provided format string.
### Method
`WriteNumber`
### Parameters
- `int?` - The nullable integer value.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## WriteTime(TimeOnly?, format, ...)
### Description
Writes a nullable `TimeOnly` value, formatted according to the provided format string.
### Method
`WriteTime`
### Parameters
- `TimeOnly?` - The nullable time value.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## WriteChar(char?, format, ...)
### Description
Writes a nullable character value, formatted according to the provided format string.
### Method
`WriteChar`
### Parameters
- `char?` - The nullable character value.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## WriteGuid(Guid?, format, ...)
### Description
Writes a nullable `Guid` value, formatted according to the provided format string.
### Method
`WriteGuid`
### Parameters
- `Guid?` - The nullable GUID value.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
```APIDOC
## WriteVersion(Version?, format, ...)
### Description
Writes a nullable `Version` value, formatted according to the provided format string.
### Method
`WriteVersion`
### Parameters
- `Version?` - The nullable version value.
- `format` - The format string.
- `...` - Additional arguments may be supported.
### Source
`RazorSlice`
```
--------------------------------
### Return RazorSlices with Null Check
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/quick-reference.md
Demonstrates returning a RazorSlice from a Minimal API endpoint, including a null check to return NotFound if the data is not found.
```csharp
app.MapGet("/user/{id}", (int id) =>
{
var user = GetUser(id);
return user == null
? Results.NotFound()
: Results.RazorSlice(user);
});
```
--------------------------------
### Write Raw HTML String
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-base.md
Use WriteHtml(string? htmlString) to write a string as raw HTML without encoding. Warning: Only use with trusted content as it does not perform HTML encoding.
```csharp
protected HtmlString WriteHtml(string? htmlString)
```
--------------------------------
### Todo Model Definition
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/razor-slice-generic.md
A simple C# class representing a Todo item with properties for Id, Title, DueDate, and IsComplete.
```csharp
public class Todo
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime DueDate { get; set; }
public bool IsComplete { get; set; }
}
```
--------------------------------
### Add RazorSlices NuGet Package Reference
Source: https://github.com/damianedwards/razorslices/blob/main/_autodocs/configuration.md
Add the RazorSlices NuGet package to your project file to include the library.
```xml
```