I want the user to be able to select a colour from the colour picker and for it to be binded to the model when the validation is correct. The validation is just that a colour is required. I can't seem to get the chosen colour binded correctly. I am using Mudblazor components on Blazor server side. I'm not using and javascript.
@using System.ComponentModel.DataAnnotations
@using MudBlazor.Utilities
<EditForm Model="@model" OnValidSubmit="OnValidSubmit">
<DataAnnotationsValidator/>
<MudGrid>
<MudItem xs="12" sm="7">
<MudCard>
<MudCardContent>
<MudTextField Label="Category Name" HelperText="Max. 20 characters" @bind-Value="model.Name" For="@(() => model.Name)"/>
<MudItem xs="12" md="6" lg="4">
<MudPaper Class="d-flex">
<MudColorPicker T="color" Rounded="true" Value="_pickerColor" ValueChanged="UpdateSelectedColor" Label="Category Colour*" Placeholder="Select Color"
ColorPickerView="ColorPickerView.Grid" DisableAlpha="true" DisableColorField="false" DisablePreview="false" DisableModeSwitch="true"
DisableSliders="true" ColorPickerMode="ColorPickerMode.HEX" />
</MudPaper>
</MudItem>
</MudCardContent>
<MudCardActions>
<MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" Class="ml-auto">Register</MudButton>
</MudCardActions>
</MudCard>
</MudItem>
<MudItem xs="12" sm="5">
<MudPaper Class="pa-4 mud-height-full">
<MudText Typo="Typo.subtitle2">Validation Summary</MudText>
@if (success)
{
<MudText Color="Color.Success">Success</MudText>
}
else
{
<MudText Color="@Color.Error">
<ValidationSummary />
</MudText>
}
</MudPaper>
</MudItem>
<MudItem xs="12">
<MudText Typo="Typo.body2" Align="Align.Center">
Fill out the form correctly to see the success message.
</MudText>
</MudItem>
</MudGrid>
</EditForm>
@code {
Category model = new Category();
public MudColor _pickerColor ;
bool success;
public class Category
{
[Required]
[StringLength(20, ErrorMessage = "Name length can't be more than 20")]
public string Name { get; set; }
[Required]
[StringLength(20, ErrorMessage = "Coloir length can't be more than 20")]
public string colour { get; set; }
}
public void UpdateSelectedColor(MudColor value)
{
_pickerColor = value;
}
private void OnValidSubmit(EditContext context)
{
success = true;
StateHasChanged();
}
}
MudColorPicker
returns a MudColor
data type. So you need to change the property type from a string
to a MudColor
.
If you want to access the hex string value from MudColor
then it is accessible via it's property Value
.
<MudColorPicker @bind-Value="model.Colour" />
@code {
Category model = new Category();
public class Category
{
[Required]
[StringLength(20, ErrorMessage = "Name length can't be more than 20")]
public string Name { get; set; }
[Required]
public MudColor Colour { get; set; }
}
}