### Install MudBlazor.StaticInput Package Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Install the MudBlazor.StaticInput package using the .NET CLI. Ensure MudBlazor is already set up in your project. ```bash dotnet add package Extensions.MudBlazor.StaticInput ``` -------------------------------- ### Install Playwright Source: https://github.com/0phois/mudblazor.staticinput/blob/master/tests/StaticInput.UnitTests/README.md Installs the necessary Playwright binaries for .NET. This command should be run from the specified path to ensure correct installation for the project's environment. ```bash pwsh ./tests/StaticInput.UnitTests/bin/Debug/net8.0/playwright.ps1 install ``` -------------------------------- ### Configure Services for StaticInput Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Register MudBlazor services and Blazor interactive components in Program.cs. This setup is required for the library to function correctly. ```csharp // Program.cs var builder = WebApplication.CreateBuilder(args); builder.Services.AddRazorComponents() .AddInteractiveWebAssemblyComponents(); // or AddInteractiveServerComponents() builder.Services.AddMudServices(); // Required: registers MudBlazor var app = builder.Build(); // ... standard pipeline ... app.Run(); ``` -------------------------------- ### Update .NET Tools Source: https://github.com/0phois/mudblazor.staticinput/blob/master/tests/StaticInput.UnitTests/README.md Ensures the global PowerShell tool is installed and updated to the latest version. This is a prerequisite for subsequent Playwright setup. ```bash dotnet tool update --global PowerShell ``` -------------------------------- ### MudStaticCheckBox Example Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Implement MudStaticCheckBox for user selection in static SSR forms. It binds to a boolean value using @bind-Value. ```html Remember Me ``` ```cs @code{ public bool RememberMe { get; set; } } ``` -------------------------------- ### MudStaticSwitch Example Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Utilize MudStaticSwitch for a toggle functionality in static SSR forms, visually distinct from checkboxes. It also uses @bind-Value for state management. ```html Remember Me ``` ```cs @code{ public bool RememberMe { get; set; } } ``` -------------------------------- ### MudStaticButton Example Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Use MudStaticButton for form actions like submit and reset in static SSR pages. It ensures correct usage within forms, similar to MudButton. ```html Login ``` -------------------------------- ### SSR Login Form with MudStaticTextField Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt This example demonstrates a typical SSR login form using MudStaticTextField for email and password inputs. It includes a password visibility toggle functionality implemented with JavaScript. ```razor @* SSR Login page — Password field with toggle-visibility adornment *@ Log In @* Required: define showPassword in a script tag or a .js file *@ @code { [SupplyParameterFromForm(FormName = "login")] private InputModel Input { get; set; } = new(); public async Task LoginUser() { var result = await SignInManager.PasswordSignInAsync( Input.Email, Input.Password, rememberMe: false, lockoutOnFailure: false); if (result.Succeeded) RedirectManager.RedirectTo("/"); } private sealed class InputModel { [Required, EmailAddress] public string Email { get; set; } = ""; [Required, DataType(DataType.Password)] public string Password { get; set; } = ""; } } ``` -------------------------------- ### Pattern A - Full Re-render Razor Component Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Example of a Razor component using Pattern A, where the entire template is rendered directly, often used for components requiring significant HTML structure changes like adding hidden inputs. ```razor @inherits MudCheckBox ``` -------------------------------- ### Pattern B - Base Passthrough Razor Component Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Example of a Razor component using Pattern B, which calls the base class's BuildRenderTree and adds parameters in the @code block. Suitable for components needing only minor annotations to the base HTML. ```razor @inherits MudTextField @{ base.BuildRenderTree(__builder); } @code { // Additional parameters and lifecycle overrides } ``` -------------------------------- ### MudStaticTextField in Static SSR Page Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Example of using MudStaticTextField within a Static Server-Side Rendering (SSR) page, such as an Identity login page. ```html ``` -------------------------------- ### Blazor Identity SSR Login Form Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt This Razor component implements a full login form for a Blazor Identity SSR application. It uses MudBlazor components for UI elements and integrates with ASP.NET Core Identity for authentication. Ensure you have the necessary Identity setup in your project. ```razor @page "/Account/Login" @using System.ComponentModel.DataAnnotations @using Microsoft.AspNetCore.Authentication @using Microsoft.AspNetCore.Identity @inject SignInManager SignInManager @inject ILogger Logger @inject NavigationManager NavigationManager @inject IdentityRedirectManager RedirectManager Log in @if (!string.IsNullOrEmpty(_errorMessage)) { @_errorMessage } Sign In Forgot password? Sign In @code { private string? _errorMessage; [CascadingParameter] private HttpContext HttpContext { get; set; } = default!; [SupplyParameterFromForm(FormName = "login")] private InputModel Input { get; set; } = new(); [SupplyParameterFromQuery] private string? ReturnUrl { get; set; } protected override async Task OnInitializedAsync() { if (HttpMethods.IsGet(HttpContext.Request.Method)) await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); } public async Task LoginUser() { var result = await SignInManager.PasswordSignInAsync( Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { Logger.LogInformation("User {Email} logged in.", Input.Email); RedirectManager.RedirectTo(ReturnUrl); } else if (result.IsLockedOut) { RedirectManager.RedirectTo("Account/Lockout"); } else { _errorMessage = "Invalid email or password."; } } private sealed class InputModel { [Required, EmailAddress] public string Email { get; set; } = ""; [Required, DataType(DataType.Password)] public string Password { get; set; } = ""; public bool RememberMe { get; set; } } } ``` -------------------------------- ### JavaScript Initialization Module Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Loads and initializes MudBlazor static components, handling Blazor Enhanced Navigation and dynamically added elements using MutationObserver. ```javascript export function afterWebStarted(blazor) { blazor?.addEventListener('enhancedload', () => initialize()); initialize(); const observer = new MutationObserver(() => initialize()); observer.observe(document.body, { childList: true, subtree: true }); } function initialize() { initTextFields(); initCheckBoxes(); initSwitches(); initRadios(); initDrawers(); initNavGroups(); } ``` -------------------------------- ### Create .razor File for Static Component (Pattern B) Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Implements the Razor component using Pattern B, inheriting from MudSelect. Handles parameter binding and conditional attribute setting for static contexts. ```razor @namespace MudBlazor.StaticInput @typeparam T @inherits MudSelect @{ base.BuildRenderTree(__builder); } @code { [Parameter] public Expression>? ValueExpression { get; set; } private string _name = string.Empty; protected override void OnInitialized() { var expression = ValueExpression?.ToString(); var index = expression?.LastIndexOf(").", StringComparison.Ordinal) ?? -1; if (index > 0) _name = expression![(index + 2)..]; base.OnInitialized(); } protected override void OnParametersSet() { if (IsStatic()) { UserAttributes["data-mud-static-type"] = "select"; UserAttributes["name"] = _name; } else { UserAttributes.Remove("data-mud-static-type"); UserAttributes.Remove("data-mud-static-initialized"); } base.OnParametersSet(); } } ``` -------------------------------- ### Register MudBlazor Services Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Register MudBlazor services in your application's Program.cs file to enable its functionality. ```csharp builder.Services.AddMudServices(); ``` -------------------------------- ### Create .razor.cs Partial Class for Static Component Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Handles context detection and property hiding for a new static component. Includes cascading HttpContext and conditional logic for .NET 9+. ```csharp using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Http; namespace MudBlazor.StaticInput; public partial class MudStaticSelect : MudSelect { [CascadingParameter] private HttpContext HttpContext { get; set; } = default!; private bool IsStatic() { #if NET9_0_OR_GREATER return !RendererInfo.IsInteractive; #else return HttpContext != null; #endif } /*********************************************** * Hide these inherited properties to prevent * * consumers from modifying them directly. * ***********************************************/ protected new EventCallback ValueChanged { get; set; } protected new EventCallback> SelectedValuesChanged { get; set; } } ``` -------------------------------- ### Consumer Usage of MudStaticCheckBox Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Demonstrates how to use the MudStaticCheckBox component by providing a lambda expression to the 'For' parameter, which maps to ValueExpression. ```razor ``` -------------------------------- ### Initialize Static Selects in JavaScript Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Adds an initSelects() function to .lib.module.js to handle DOM behavior for static select components. Stamps elements to prevent double initialization and wires up a change event listener. ```javascript function initialize() { // ... existing init calls ... initSelects(); } function initSelects() { const selects = document.querySelectorAll( '[data-mud-static-type="select"]:not([data-mud-static-initialized="true"])' ); selects.forEach(selectElement => { // Stamp immediately to prevent double-init selectElement.setAttribute('data-mud-static-initialized', 'true'); // Wire up DOM behaviour without JS interop selectElement.addEventListener('change', () => { // e.g. update aria-selected state, sync visual indicators }); }); } ``` -------------------------------- ### Control MudBlazor Drawers with JavaScript Interop Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Use MudDrawerInterop functions to programmatically manage drawer states. State is persisted in localStorage and session cookies. ```javascript MudDrawerInterop.toggleDrawer('main-nav-drawer'); ``` ```javascript MudDrawerInterop.setDrawerState('main-nav-drawer', true); ``` ```javascript MudDrawerInterop.syncDrawerState('main-nav-drawer', false); ``` ```javascript const isOpen = MudDrawerInterop.getDrawerState('main-nav-drawer'); console.log('Drawer is', isOpen ? 'open' : 'closed'); ``` ```javascript window.addEventListener('resize', () => { if (window.innerWidth < 600) { MudDrawerInterop.setDrawerState('main-nav-drawer', false); } }); ``` -------------------------------- ### Ensure MudBlazor Providers in App.razor Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Include the necessary MudBlazor providers in your App.razor file to ensure MudBlazor components are correctly initialized. ```razor @* App.razor — ensure MudBlazor providers are present *@ ``` -------------------------------- ### Manage Static Component Attributes Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md This method updates the `UserAttributes` dictionary to pass configuration data to JavaScript for static rendering. It adds specific attributes when static and removes them when interactive to ensure correct behavior and prevent double-initialization. ```csharp protected override void OnParametersSet() { if (IsStatic()) { UserAttributes["data-mud-static-type"] = "checkbox"; UserAttributes["data-mud-static-name"] = _name; } else { UserAttributes.Remove("data-mud-static-type"); UserAttributes.Remove("data-mud-static-initialized"); } base.OnParametersSet(); } ``` -------------------------------- ### Persist State During SSR Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Register a callback to persist component state during Server-Side Rendering (SSR). This state is then available during interactive startup. ```csharp // During SSR — write state _subscription = PersistentState.RegisterOnPersisting(() => { PersistentState.PersistAsJson(storageKey, _open); return Task.CompletedTask; }, PersistMode); // During interactive startup — read state if (PersistentState.TryTakeFromJson(storageKey, out var restored)) { _open = restored; } ``` -------------------------------- ### MudStaticRadioGroup for Option Selection Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md MudStaticRadioGroup allows users to select a single option from a predefined set. Customize the color for the group and individual radio buttons. ```html Option 1 Option 2 ``` ```cs @code { public string SelectedOption { get; set; } = "Option 1"; } ``` -------------------------------- ### Property Hiding with 'protected new' in C# Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Hides interactive MudBlazor properties that are incompatible with static mode using 'protected new' to prevent accidental usage by consumers. ```csharp // In MudStaticTextField.razor.cs protected new bool Clearable { get; set; } protected new bool Immediate { get; set; } protected new EventCallback TextChanged { get; set; } protected new EventCallback OnBlur { get; set; } // ... and many more ``` -------------------------------- ### MudDrawerInterop API Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt The `MudDrawerInterop` object provides several methods for controlling MudDrawers from JavaScript. These methods allow you to toggle drawers, set their state to open or closed, synchronize their state with persisted storage, and retrieve their current state. ```APIDOC ## JavaScript Interop API (`MudDrawerInterop`) The library exposes a global `window.MudDrawerInterop` object for programmatic drawer control from custom JavaScript. State is always mirrored to both `localStorage` and a session cookie. ### Methods #### `toggleDrawer(drawerId)` **Description**: Toggles the open/closed state of a drawer identified by its HTML id. **Parameters**: - `drawerId` (string) - The HTML id of the drawer to toggle. **Example**: ```javascript MudDrawerInterop.toggleDrawer('main-nav-drawer'); ``` #### `setDrawerState(drawerId, isOpen)` **Description**: Forces a drawer to a specific state (open or closed). **Parameters**: - `drawerId` (string) - The HTML id of the drawer. - `isOpen` (boolean) - `true` to open the drawer, `false` to close it. **Example**: ```javascript MudDrawerInterop.setDrawerState('main-nav-drawer', true); ``` #### `syncDrawerState(drawerId, initialState)` **Description**: Syncs the stored state without touching the DOM. This is used internally when the `Open` parameter changes in interactive mode. **Parameters**: - `drawerId` (string) - The HTML id of the drawer. - `initialState` (boolean) - The initial state to sync. **Example**: ```javascript MudDrawerInterop.syncDrawerState('main-nav-drawer', false); ``` #### `getDrawerState(drawerId)` **Description**: Reads the persisted open/closed state from `localStorage` or a session cookie. **Parameters**: - `drawerId` (string) - The HTML id of the drawer. **Returns**: - (boolean) - `true` if the drawer is open, `false` if closed. **Example**: ```javascript const isOpen = MudDrawerInterop.getDrawerState('main-nav-drawer'); console.log('Drawer is', isOpen ? 'open' : 'closed'); ``` ### Usage Example ```javascript // Example: close all drawers on mobile breakpoint via custom logic window.addEventListener('resize', () => { if (window.innerWidth < 600) { MudDrawerInterop.setDrawerState('main-nav-drawer', false); } }); ``` ``` -------------------------------- ### Update Cookie and Local Storage Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Use this JavaScript function to update both local storage and cookies simultaneously. This ensures state is maintained across server and client. ```javascript function updateStorage(key, value) { localStorage.setItem(key, value); document.cookie = `${key}=${value}; path=/; SameSite=Lax`; } ``` -------------------------------- ### MudStaticCheckBox in Registration Form Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Demonstrates using MudStaticCheckBox within an EditForm for a registration process. The 'For' expression is crucial for binding and the hidden input trick ensures the 'AcceptTerms' value is always submitted. ```razor @* Registration form with a "Remember Me" checkbox *@ I accept the terms and conditions Register @code { [SupplyParameterFromForm(FormName = "register")] private InputModel Input { get; set; } = new(); private sealed class InputModel { [Required, EmailAddress] public string Email { get; set; } = ""; [Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the terms.")] public bool AcceptTerms { get; set; } } public async Task RegisterUser() { // Input.AcceptTerms is always bound — true when checked, false when unchecked // because of the hidden input emitting "False" when the checkbox is not checked await UserService.RegisterAsync(Input.Email); } } ``` -------------------------------- ### MudStaticNavGroup for Collapsible Navigation Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md MudStaticNavGroup allows for collapsible sections within a MudNavMenu. It can be nested and its expanded state can be controlled. ```html Dashboard Servers Billing Users Security About ``` -------------------------------- ### MudStaticButton Form Actions Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Demonstrates the usage of `MudStaticButton` with different `FormAction` values: `Submit` for standard form submission, `Reset` for clearing form fields, and `Post` for standalone form submissions with antiforgery tokens. ```razor @* Demonstrating all three FormAction values *@ @* 1. Submit — inside EditForm *@ Save Clear @* 2. Post — standalone antiforgery-protected form (e.g. identity logout) *@ Sign Out @code { [SupplyParameterFromForm(FormName = "demo")] private DemoModel Model { get; set; } = new(); private sealed class DemoModel { public string Name { get; set; } = ""; } private Task Save() => Task.CompletedTask; } ``` -------------------------------- ### Navigation Sidebar with Collapsible Groups Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Creates a navigation sidebar featuring collapsible groups using `MudStaticNavGroup`. This component utilizes pure CSS and JavaScript for toggling, requiring no SignalR or WASM. ```razor @* Navigation sidebar with collapsible groups *@ Dashboard Users Security Billing Monthly Annual Sign Out ``` -------------------------------- ### MudStaticSwitch in Settings Form Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Illustrates the use of MudStaticSwitch components in an EditForm for managing user settings. It showcases different color options and the 'Typo' parameter for label styling. The hidden input mechanism ensures correct model binding for boolean states. ```razor @* Settings form with notification and marketing toggles *@ Save Reset @code { [SupplyParameterFromForm(FormName = "settings")] private SettingsModel Settings { get; set; } = new(); private sealed class SettingsModel { public bool EmailNotifications { get; set; } = true; public bool MarketingEmails { get; set; } } public Task SaveSettings() { // Settings.EmailNotifications and Settings.MarketingEmails are correctly bound // regardless of checked/unchecked state due to the hidden input trick return UserSettingsService.UpdateAsync(Settings); } } ``` -------------------------------- ### localStorage Fallback for WASM Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md In OnAfterRenderAsync, check localStorage for state if the component is not static. This handles WASM scenarios where pre-rendering might not have occurred. ```csharp protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender && !IsStatic()) { var stored = await JsRuntime.InvokeAsync("localStorage.getItem", storageKey); if (stored != null && bool.Parse(stored) != _open) { _open = bool.Parse(stored); await OpenChanged.InvokeAsync(_open); StateHasChanged(); } } } ``` -------------------------------- ### Responsive Sidebar with SSR-Safe Toggle Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Implements a responsive sidebar with an SSR-safe hamburger toggle button. The toggle state is persisted across SSR requests using cookies, `PersistentComponentState`, and `localStorage`. ```razor @* MainLayout.razor — responsive sidebar with SSR-safe toggle *@ @inherits LayoutComponentBase My App Home Account @Body @code { private bool _drawerOpen = true; } ``` -------------------------------- ### MudStaticNavDrawerToggle for Drawer Control Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Use MudStaticNavDrawerToggle to control the opening and closing of a MudDrawer. It can also manage responsive drawer behavior based on page size. ```html Store Library Community ``` -------------------------------- ### MudStaticRadioGroup with Typed Radio Buttons Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Implements a survey form using MudStaticRadioGroup and MudStaticRadio for user satisfaction selection. Ensures a value is always bound by emitting a hidden input, and uses DataAnnotations for validation. ```razor @* Survey form with a typed radio group *@ How satisfied are you with our service? Very Satisfied Satisfied Neutral Unsatisfied Very Unsatisfied Submit Survey @code { [SupplyParameterFromForm(FormName = "survey")] private SurveyModel Survey { get; set; } = new() { Satisfaction = "neutral" }; private sealed class SurveyModel { [Required(ErrorMessage = "Please select a satisfaction level.")] public string Satisfaction { get; set; } = ""; } public Task SubmitSurvey() => SurveyService.RecordAsync(Survey.Satisfaction); } ``` -------------------------------- ### Expression-Driven Naming in C# Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Extracts the property name from a ValueExpression to be used as the input's name attribute. This is crucial for server-side model binding in static components. ```csharp [Parameter] public Expression>? ValueExpression { get; set; } protected override void OnInitialized() { var expression = ValueExpression?.ToString(); var index = expression?.LastIndexOf(").", StringComparison.Ordinal) ?? -1; if (index > 0) { _name = expression![(index + 2)..]; // e.g. "Input.RememberMe" } } ``` -------------------------------- ### MudStaticTextField for Password Input Source: https://github.com/0phois/mudblazor.staticinput/blob/master/README.md Use MudStaticTextField for secure password input. It supports toggling visibility with custom icons and click functions. ```html ``` ```cs @code { public string Password { get; set; } } ``` ```js ``` -------------------------------- ### MudStaticButton Form Actions Source: https://context7.com/0phois/mudblazor.staticinput/llms.txt Demonstrates the three FormAction modes (Submit, Reset, Post) for MudStaticButton. Use Submit within an existing EditForm, Reset to clear form fields, and Post for standalone forms requiring an antiforgery token. ```razor @* Identity UI action buttons demonstrating all three FormAction modes *@ @* Submit inside an existing EditForm *@ Save Profile Reset @* Post — standalone form with antiforgery token, useful for logout etc. *@ Log Out @code { [SupplyParameterFromForm(FormName = "profile")] private ProfileModel Input { get; set; } = new(); private sealed class ProfileModel { [Required] public string DisplayName { get; set; } = ""; } public Task HandleSubmit() => ProfileService.UpdateAsync(Input); } ``` -------------------------------- ### Detect Blazor SSR Rendering Context Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md This method determines if the component is rendering in a static SSR context. It uses `RendererInfo.IsInteractive` for .NET 9+ and checks for `HttpContext` presence for .NET 8. ```csharp private bool IsStatic() { #if NET9_0_OR_GREATER return !RendererInfo.IsInteractive; #else return HttpContext != null; #endif } ``` -------------------------------- ### Hidden Input Trick for Checkboxes Source: https://github.com/0phois/mudblazor.staticinput/blob/master/Onboarding.md Implements a hidden input field that submits 'False' when the checkbox is unchecked, ensuring the field is always present in the form payload. ```razor ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.