Skip to content

Commit 087a7cc

Browse files
Merge branch 'development' into 991709-ie
2 parents 8067eb6 + d2c1294 commit 087a7cc

35 files changed

+2024
-944
lines changed

blazor-toc.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2181,6 +2181,7 @@
21812181
<li><a href="/blazor/datagrid/style-and-appearance/paging">Paging</a></li>
21822182
<li><a href="/blazor/datagrid/style-and-appearance/selection">Selection</a></li>
21832183
<li><a href="/blazor/datagrid/style-and-appearance/sorting">Sorting</a></li>
2184+
<li><a href="/blazor/datagrid/style-and-appearance/toolbar">Toolbar</a></li>
21842185
</ul>
21852186
</li>
21862187
<li>How To

blazor/datagrid/data-annotation.md

Lines changed: 99 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,101 @@
11
---
22
layout: post
33
title: Data Annotation in Blazor DataGrid | Syncfusion
4-
description: Learn how to achieve data validation with data annotations in the Syncfusion Blazor DataGrid component.
4+
description: Learn how to use Data Annotations for validation and column metadata in Syncfusion Blazor DataGrid, including enum display and CRUD form validation.
55
platform: Blazor
66
control: DataGrid
77
documentation: ug
88
---
99

1010
# Data Annotation in Blazor DataGrid
1111

12-
Data Annotations are used to define validation rules for model classes or properties, ensuring that data entered into an application conforms to the expected format and meets specific criteria. They also enable the display of appropriate error messages to end users.
12+
Data annotations define validation and display rules for model classes or properties in the Syncfusion<sup style="font-size:70%">&reg;</sup> Blazor DataGrid. These attributes ensure that input values follow specific formats and constraints while providing clear error messages during editing operations.
1313

14-
In the Syncfusion<sup style="font-size:70%">&reg;</sup> Blazor DataGrid, Data Annotations are leveraged to automatically map these validation rules to the corresponding [GridColumn](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html) properties. This integration provides seamless data validation during editing operations within the Grid.
14+
When the DataGrid is bound to a model, data annotations automatically map to corresponding [GridColumn](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.GridColumn.html) settings. This enables built-in validation and metadata display during CRUD operations.
1515

16-
To enable Data Annotations for validation in a Grid, you need to refer the **System.ComponentModel.DataAnnotations** namespace in your Blazor application. Once enabled, the Grid automatically uses the data annotations applied to your model class properties to perform data validation.
16+
To enable data annotation in the Blazor DataGrid:
1717

18-
The following table lists the data annotation attributes supported in the Grid:
18+
1. Add the **System.ComponentModel.DataAnnotations** namespace in the Blazor application.
19+
2. Bind the DataGrid to a model using `TValue` and [DataSource](https://help.syncfusion.com/cr/blazor/Syncfusion.Blazor.Grids.SfGrid-1.html#Syncfusion_Blazor_Grids_SfGrid_1_DataSource).
20+
3. Apply annotation attributes to model properties to enforce validation and display rules during CRUD operations.
21+
22+
### Supported Data Annotation Attributes
23+
24+
The tables categorize supported attributes by display, formatting, metadata, and validation functionality.
25+
26+
### Display Attributes
27+
28+
Use **Display** attributes to control how column headers, ordering, and metadata appear in the grid interface.
29+
30+
| Attribute Name | Properties | Functionality |
31+
|----------------|------------|---------------|
32+
| Display | Name | Sets the header text for the DataGrid column |
33+
| Display | ShortName | Sets a shorter version of the header text |
34+
| Display | AutoGenerateField | Prevents the column from being auto-generated |
35+
| Display | AutoGenerateFilter | Disables filtering for the column |
36+
| Display | Description | Sets tooltip text shown on column ellipsis hover |
37+
| Display | Order | Defines the display order of the column |
38+
39+
### DisplayFormat Attributes
40+
41+
Apply **DisplayFormat** attributes when column values require specific formatting or null-handling behavior.
1942

2043
| Attribute Name | Properties | Functionality |
21-
|---------------|------------|--------------|
22-
| Display | Name | Sets the header text for the Grid column |
23-
| Display | ShortName | Sets a shorter version of the header text for the Grid column |
24-
| Display | AutoGenerateField | Prevents the column from being auto-generated in the Grid |
25-
| Display | AutoGenerateFilter | Specifies whether filtering should be disabled for the column |
26-
| Display | Description | Sets the tooltip text displayed when hovering over the column ellipsis |
27-
| Display | Order | Defines the display order priority of the Grid column |
28-
| DisplayFormat | FormatString | Sets the format for displaying data in the column |
29-
| DisplayFormat | ApplyFormatInEditMode | Determines whether the format should be applied during edit mode |
30-
| DisplayFormat | NullDisplayText | Sets the text to be displayed when the value of the property is null |
31-
| DisplayFormat | ConvertEmptyStringToNull | Determines whether empty string values should be converted to null in the user interface |
32-
| DisplayFormat | NeedsHtmlEncode | Sets whether HTML encoding should be disabled for a particular column |
33-
| ScaffoldColumnAttribute | Scaffold | Sets whether the column is visible in the user interface |
34-
| EditableAttribute | ReadOnly | Sets whether the column allows editing |
35-
| Key | Key | Marks a column as the primary key in the Grid |
36-
| Validation Attributes:<br><br>1. RequiredAttribute<br>2. StringLengthAttribute<br>3. RangeAttribute<br>4. RegularExpressionAttribute<br>5. MinLengthAttribute<br>6. MaxLengthAttribute<br>7. EmailAddressAttribute<br>8. CompareAttribute<br> | | These validation attributes are used as `validation rules` in Grid CRUD operations |
37-
38-
> The Syncfusion<sup style="font-size:70%">&reg;</sup> Blazor DataGrid property takes precedence over data annotation attributes. For example, when both the DisplayName attribute and `HeaderText` are assigned to a field in the Grid model class for a specific column, the `HeaderText` value will be prioritized and displayed in the Grid header.
39-
40-
The following sample code demonstrates how to use data annotations in the Grid:
44+
|----------------|------------|---------------|
45+
| DisplayFormat | FormatString | Sets the display format for column data |
46+
| DisplayFormat | ApplyFormatInEditMode | Applies format during edit mode |
47+
| DisplayFormat | NullDisplayText | Displays custom text when the value is null |
48+
| DisplayFormat | ConvertEmptyStringToNull | Converts empty strings to null in the UI |
49+
| DisplayFormat | HtmlEncode | Enables or disables HTML encoding for display |
50+
51+
### Other Metadata Attributes
52+
53+
Use these attributes to manage column visibility, editing behavior, and key definitions.
54+
55+
| Attribute Name | Properties | Functionality |
56+
|----------------|------------|---------------|
57+
| ScaffoldColumnAttribute | Scaffold | Controls column visibility in the UI |
58+
| ReadOnlyAttribute | IsReadOnly | Prevents editing of the column |
59+
| Key | Key | Marks the column as the primary key |
60+
61+
### Validation Attributes
62+
63+
Add validation attributes to enforce rules that display inline Blazor DataGrid validation messages during CRUD operations.
64+
65+
- RequiredAttribute
66+
- StringLengthAttribute
67+
- RangeAttribute
68+
- RegularExpressionAttribute
69+
- MinLengthAttribute
70+
- MaxLengthAttribute
71+
- EmailAddressAttribute
72+
- CompareAttribute
73+
74+
> When both the `Display` attribute’s `Name` and the column’s `HeaderText` property are defined, the `HeaderText` value takes precedence and is shown in the column header.
75+
76+
The `Display` attribute can be used to show user-friendly labels for enum values. This improves readability by replacing raw enum values with descriptive names.
4177

4278
{% tabs %}
4379
{% highlight razor tabtitle="Index.razor" %}
4480

4581
@using Syncfusion.Blazor.Grids
4682
@using Syncfusion.Blazor.DropDowns
4783
@using System.Reflection
48-
@using System.ComponentModel.DataAnnotations;
84+
@using System.ComponentModel.DataAnnotations
4985

5086
<SfGrid TValue="Order" DataSource="@Orders" Height="315" AllowPaging="true" AllowFiltering="true" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })">
5187
<GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true"></GridEditSettings>
5288
<GridColumns>
53-
<GridColumn Field=@nameof(Order.OrderID) TextAlign="TextAlign.Right" Width="115"></GridColumn>
89+
<GridColumn Field=@nameof(Order.OrderID) IsPrimaryKey="true" TextAlign="TextAlign.Right" Width="115"></GridColumn>
5490
<GridColumn Field=@nameof(Order.CustomerID) Width="120"></GridColumn>
5591
<GridColumn Field=@nameof(Order.OrderDate) EditType="EditType.DatePickerEdit" Format="d" TextAlign="TextAlign.Right" Width="130" Type="ColumnType.Date"></GridColumn>
5692
<GridColumn Field=@nameof(Order.Freight) HeaderText="Freight" TextAlign="TextAlign.Right" Format="C2" Width="115"></GridColumn>
5793
<GridColumn Field=@nameof(Order.ShipCity) Width="120"></GridColumn>
5894
<GridColumn Field=@nameof(Order.Verified) Width="110">
5995
<EditTemplate>
6096
@{
61-
var Order = (context as Order);
62-
<SfDropDownList Placeholder="Type" ID="Type" @bind-Value="@((context as Order).Verified)" DataSource="@DropDownData" TValue="Status" TItem="Data">
63-
<DropDownListEvents TItem="Data" TValue="Status"></DropDownListEvents>
97+
var CurrentOrder = (context as Order);
98+
<SfDropDownList Placeholder="Type" ID="Type" @bind-Value="CurrentOrder.Verified" DataSource="@DropDownData" TValue="Status" TItem="Data">
6499
<DropDownListFieldSettings Value="Value" Text="Type"></DropDownListFieldSettings>
65100
</SfDropDownList>
66101
}
@@ -70,56 +105,60 @@ The following sample code demonstrates how to use data annotations in the Grid:
70105
</SfGrid>
71106

72107
@code {
73-
public List<Order> Orders { get; set; }
74-
public List<Data> DropDownData = new List<Data>();
108+
private List<Order> Orders { get; set; }
109+
private List<Data> DropDownData { get; } = new();
75110

76111
protected override void OnInitialized()
77112
{
78-
Random rnd = new Random();
79-
var values = Enum.GetValues(typeof(Status));
80-
foreach (Status item in Enum.GetValues(typeof(Status)))
113+
var Rnd = new Random();
114+
var Values = Enum.GetValues(typeof(Status));
115+
116+
foreach (Status Item in Values)
81117
{
82-
DropDownData.Add(new Data { Type = GetDisplayName(item), Value = item });
118+
DropDownData.Add(new Data { Type = GetDisplayName(Item), Value = Item });
83119
}
84-
Orders = Enumerable.Range(1, 75).Select(x => new Order()
120+
121+
Orders = Enumerable.Range(1, 75).Select(x => new Order
85122
{
86123
OrderID = 1000 + x,
87-
CustomerID = (new string[] { "ALFKI", "ANANTR", "ANTON", string.Empty, null })[new Random().Next(5)],
124+
CustomerID = (new string[] { "ALFKI", "ANANTR", "ANTON", string.Empty, null })[Rnd.Next(5)],
88125
Freight = 2.1 * x,
89126
OrderDate = DateTime.Now.AddDays(-x),
90-
ShipCity = (new string[] { "Berlin", "Madrid", "Cholchester", "Marseille", "Tsawassen" })[new Random().Next(5)],
91-
Verified = (Status)(values.GetValue(rnd.Next(values.Length))),
127+
ShipCity = (new string[] { "Berlin", "Madrid", "Cholchester", "Marseille", "Tsawassen" })[Rnd.Next(5)],
128+
Verified = (Status)Values.GetValue(Rnd.Next(Values.Length)),
92129
}).ToList();
93130
}
94131

95-
public static string GetDisplayName(Enum enumValue)
132+
private static string GetDisplayName(Enum EnumValue)
96133
{
97-
string displayName;
98-
displayName = enumValue.GetType()
99-
.GetMember(enumValue.ToString())
134+
var DisplayName = EnumValue.GetType()
135+
.GetMember(EnumValue.ToString())
100136
.FirstOrDefault()
101137
.GetCustomAttribute<DisplayAttribute>()?
102138
.GetName();
103-
if (String.IsNullOrEmpty(displayName))
139+
140+
if (string.IsNullOrEmpty(DisplayName))
104141
{
105-
displayName = enumValue.ToString();
142+
DisplayName = EnumValue.ToString();
106143
}
107-
return displayName;
144+
return DisplayName;
108145
}
109-
public enum Status
146+
147+
internal enum Status
110148
{
111149
[Display(Name = "Yeah")]
112150
Yes = 0,
113151
[Display(Name = "Nope")]
114152
No = 1
115153
}
116-
public class Data
154+
155+
internal sealed class Data
117156
{
118157
public string Type { get; set; }
119158
public Status Value { get; set; }
120159
}
121160

122-
public class Order
161+
internal sealed class Order
123162
{
124163
// Sets column as primary key.
125164
[Key]
@@ -128,34 +167,35 @@ The following sample code demonstrates how to use data annotations in the Grid:
128167
// Sets header text to the column.
129168
[Display(ShortName = "ID")]
130169
public int OrderID { get; set; }
170+
131171
[Display(Name = "CustomerID", Description ="List of Customers")]
132172
// Sets column as required and error message to be displayed when empty.
133173
[Required(ErrorMessage = "Field should not be empty")]
134174
[DisplayFormat(NullDisplayText = "Empty", ConvertEmptyStringToNull = true)]
135-
public string? CustomerID { get; set; }
175+
public string CustomerID { get; set; }
176+
136177
// Sets data type of column as Date.
137178
[DataType(DataType.Date)]
138179
[Display(Name = "Order Date")]
139180
// Sets column as read only.
140181
[Editable(false)]
141182
public DateTime? OrderDate { get; set; }
183+
142184
[Display(Name = "Freight", AutoGenerateFilter = false)]
143185
public double? Freight { get; set; }
144-
[ScaffoldColumn(scaffold:false)]
186+
187+
[ScaffoldColumn(false)]
145188
public string ShipCity { get; set; }
189+
146190
public Status Verified { get; set; }
147191
}
148192
}
149193

150194
{% endhighlight %}
151195
{% endtabs %}
152196

153-
{% previewsample "https://blazorplayground.syncfusion.com/embed/LthIZotuimdZMRyd?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
154-
155-
The following image shows how Data Annotations are applied to Grid columns in a Blazor application:
156-
157-
![Data Annotation in Grid](./images/blazor-datagrid-data-annotation.png)
197+
{% previewsample "https://blazorplayground.syncfusion.com/embed/rXLIijigsHQsZoWd?appbar=false&editor=false&result=true&errorlist=false&theme=bootstrap5" %}
158198

159-
> The **Verified** column displays the `Enum` member using the `Display` attribute name, enhancing user experience by rendering a human-readable label instead of the raw enum value.
199+
![Data annotations in DataGrid](./images/blazor-datagrid-data-annotation.png)
160200

161-
> You can refer to our [Syncfusion<sup style="font-size:70%">&reg;</sup> Blazor DataGrid](https://www.syncfusion.com/blazor-components/blazor-datagrid) feature tour page for its features. You can also explore our [Syncfusion<sup style="font-size:70%">&reg;</sup> Blazor DataGrid example](https://blazor.syncfusion.com/demos/datagrid/overview?theme=bootstrap5) to understand how to present and manipulate data.
201+
N> Refer to the [Syncfusion<sup style="font-size:70%">&reg;</sup> Blazor DataGrid](https://www.syncfusion.com/blazor-components/blazor-datagrid) feature tour for an overview of available features. Explore the [Blazor DataGrid example](https://blazor.syncfusion.com/demos/datagrid/overview?theme=bootstrap5) to see how data is presented and managed within an application.

0 commit comments

Comments
 (0)