Button¶
The Button component displays a push button control that allows users to trigger actions. It may seem strange that we have a Button component when there already is an HTML button and Blazor has features that enable C# interactions with that button, but we need to activate other features that were once present in Web Forms, such as OnCommand event bubbling, OnClientClick JavaScript execution, and CausesValidation support.
Original Microsoft documentation: https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.button?view=netframework-4.8
Features Supported in Blazor¶
Text- the text displayed on the buttonOnClick- event handler triggered when button is clickedOnClientClick- JavaScript code to execute on client-side clickOnCommand- event handler with event bubbling, receivesCommandEventArgswithCommandNameandCommandArgumentCommandName- the command name passed toOnCommandeventCommandArgument- the command argument passed toOnCommandeventCausesValidation- controls whether form validation is triggered on click (default:true)ValidationGroup- specifies the validation group for which the button triggers validationEnabled- enables or disables the buttonVisible- controls button visibilityToolTip- tooltip text displayed on hover- All style properties (
BackColor,ForeColor,BorderColor,BorderStyle,BorderWidth,CssClass,Width,Height,Font)
Blazor Notes¶
- The
OnCommandevent uses aCommandEventArgsclass that containsCommandNameandCommandArgumentproperties - When
CommandNameis set, clicking the button triggersOnCommandinstead ofOnClick - Event bubbling is supported for container components that need to handle commands from child buttons
Web Forms Features NOT Supported¶
- PostBackUrl - Not supported; Blazor uses component events instead of postbacks to different pages
- UseSubmitBehavior - Not supported; Blazor buttons trigger click events and you can inspect the form regardless
- AccessKey - Use HTML
accesskeyattribute directly if needed
Web Forms Declarative Syntax¶
<asp:Button
AccessKey="string"
BackColor="color name|#dddddd"
BorderColor="color name|#dddddd"
BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset"
BorderWidth="size"
CausesValidation="True|False"
CommandArgument="string"
CommandName="string"
CssClass="string"
Enabled="True|False"
EnableTheming="True|False"
EnableViewState="True|False"
Font-Bold="True|False"
Font-Italic="True|False"
Font-Names="string"
Font-Overline="True|False"
Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|
Large|X-Large|XX-Large"
Font-Strikeout="True|False"
Font-Underline="True|False"
ForeColor="color name|#dddddd"
Height="size"
ID="string"
OnClick="Click event handler"
OnClientClick="string"
OnCommand="Command event handler"
OnDataBinding="DataBinding event handler"
OnDisposed="Disposed event handler"
OnInit="Init event handler"
OnLoad="Load event handler"
OnPreRender="PreRender event handler"
OnUnload="Unload event handler"
PostBackUrl="uri"
runat="server"
SkinID="string"
Style="string"
TabIndex="integer"
Text="string"
ToolTip="string"
UseSubmitBehavior="True|False"
ValidationGroup="string"
Visible="True|False"
Width="size"
/>
Blazor Razor Syntax¶
Basic Button with Click Event¶
<Button Text="Click Me" OnClick="HandleClick" />
@code {
void HandleClick()
{
// Handle the click
}
}
Button with Command¶
<Button Text="Save"
CommandName="Save"
CommandArgument="@itemId"
OnCommand="HandleCommand" />
@code {
private string itemId = "123";
void HandleCommand(CommandEventArgs args)
{
var command = args.CommandName; // "Save"
var argument = args.CommandArgument; // "123"
}
}
Button with JavaScript Click¶
Styled Button¶
<Button Text="Styled Button"
BackColor="WebColor.Blue"
ForeColor="WebColor.White"
Font_Bold="true"
CssClass="my-button-class" />
Disabled Button¶
Button with Validation Control¶
<EditForm Model="@model" OnValidSubmit="HandleSubmit">
<TextBox @bind-Text="model.Name" />
<RequiredFieldValidator ControlToValidate="..." Text="Required" />
@* This button triggers validation *@
<Button Text="Submit" CausesValidation="true" />
@* This button skips validation *@
<Button Text="Cancel" CausesValidation="false" OnClick="HandleCancel" />
</EditForm>
ValidationGroup - Selective Validation¶
The ValidationGroup property allows you to create multiple validation groups on a single form. When a button with a ValidationGroup is clicked, only validators with the matching ValidationGroup will be triggered.
Important: To use ValidationGroup, you must wrap your form in a ValidationGroupProvider component.
@using BlazorWebFormsComponents.Validations
<ValidationGroupProvider>
<EditForm Model="@model" OnValidSubmit="HandlePersonalSubmit">
@* Personal Information Group *@
<InputText @ref="NameInput.Current" @bind-Value="model.Name" />
<RequiredFieldValidator ControlToValidate="@NameInput"
Text="Name required"
ValidationGroup="Personal" />
<InputText @ref="EmailInput.Current" @bind-Value="model.Email" />
<RequiredFieldValidator ControlToValidate="@EmailInput"
Text="Email required"
ValidationGroup="Personal" />
<Button Text="Validate Personal" ValidationGroup="Personal" />
</EditForm>
<EditForm Model="@model" OnValidSubmit="HandleBusinessSubmit">
@* Business Information Group *@
<InputText @ref="CompanyInput.Current" @bind-Value="model.Company" />
<RequiredFieldValidator ControlToValidate="@CompanyInput"
Text="Company required"
ValidationGroup="Business" />
<Button Text="Validate Business" ValidationGroup="Business" />
</EditForm>
</ValidationGroupProvider>
@code {
ForwardRef<InputBase<string>> NameInput = new ForwardRef<InputBase<string>>();
ForwardRef<InputBase<string>> EmailInput = new ForwardRef<InputBase<string>>();
ForwardRef<InputBase<string>> CompanyInput = new ForwardRef<InputBase<string>>();
private FormModel model = new FormModel();
void HandlePersonalSubmit() { /* Personal validation passed */ }
void HandleBusinessSubmit() { /* Business validation passed */ }
}
How ValidationGroup Works:
- Same Group - Button with
ValidationGroup="Personal"triggers only validators withValidationGroup="Personal" - No Group (empty/null) - Button without a
ValidationGrouptriggers only validators without aValidationGroup - Multiple Groups - You can have multiple groups on the same page that validate independently
- CausesValidation - Set
CausesValidation="false"to disable validation entirely for a button
HTML Output¶
Web Forms Input:
Rendered HTML:
Styled Button Input:
Rendered HTML:
Migration Notes¶
When migrating from Web Forms to Blazor:
- Remove
asp:prefix - Change<asp:Button>to<Button> - Remove
runat="server"- Not needed in Blazor - Remove
IDattribute - Use@refif you need a reference to the component - Update event handler syntax - Change
OnClick="btnSubmit_Click"toOnClick="HandleClick" - Replace
PostBackUrl- Use navigation or component state instead - Update
OnCommandhandlers - The signature changes from(object sender, CommandEventArgs e)to(CommandEventArgs args)
Before (Web Forms)¶
<asp:Button ID="btnSave"
Text="Save"
OnClick="btnSave_Click"
CssClass="btn btn-primary"
runat="server" />
After (Blazor)¶
<Button Text="Save"
OnClick="HandleSave"
CssClass="btn btn-primary" />
@code {
void HandleSave()
{
// Handle click
}
}
Examples¶
Basic Click Handler¶
<Button Text="Click Me!" OnClick="OnClick" />
<span style="font-weight: bold">@message</span>
@code {
private string message = "Not clicked yet!";
void OnClick()
{
message = "I've been clicked!";
}
}
Command Pattern with Multiple Buttons¶
<Button Text="Edit" CommandName="Edit" CommandArgument="@item.Id" OnCommand="HandleCommand" />
<Button Text="Delete" CommandName="Delete" CommandArgument="@item.Id" OnCommand="HandleCommand" />
<p>Last action: @lastAction</p>
@code {
private string lastAction = "None";
void HandleCommand(CommandEventArgs args)
{
lastAction = $"Command '{args.CommandName}' on item {args.CommandArgument}";
}
}
Styled Buttons¶
@using static BlazorWebFormsComponents.WebColor
<Button Text="Blue Button" BackColor="Blue" ForeColor="White" />
<Button Text="Red Bold Button" BackColor="Red" ForeColor="Yellow" Font_Bold="true" />
<Button Text="Custom Class" CssClass="rounded-corners" />
JavaScript Integration¶
<Button Text="Show Alert" OnClientClick="alert('Hello from JavaScript!')" />
<Button Text="Confirm" OnClientClick="return confirm('Are you sure?')" OnClick="HandleConfirmed" />
See Also¶
- LinkButton - A button that renders as a hyperlink
- ImageButton - A button that displays an image
- RequiredFieldValidator - Validate required fields
- Live Demo - Interactive Button samples