-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Blazor supports DisplayName for models
#64636
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ilonatommy
wants to merge
14
commits into
dotnet:main
Choose a base branch
from
ilonatommy:fix-49147
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+526
−17
Open
Changes from 3 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
ba210fd
API proposal.
ilonatommy 46795d5
Unit tests.
ilonatommy a167497
Add E2E tests.
ilonatommy 60aa7f7
Alphabetically.
ilonatommy db4d8af
Update templates to use the new feature.
ilonatommy 11da419
Cleanup.
ilonatommy 7bfb44c
Update src/Components/Web/src/Forms/DisplayNameLabel.cs
ilonatommy dc39fdc
Allign null operations.
ilonatommy b048f80
Feedback: remove `Label` from the name to avoid misunderstandings.
ilonatommy ce68d5a
Fix merge error
ilonatommy a8098f9
Feedback: use same caching approach as `FieldIdentifier` uses.
ilonatommy b6195cc
Fix build.
ilonatommy dfec213
Feedback: use the infrastructure from `ValidationMessage`.
ilonatommy 5a4421f
Feedback: Make sure localization is supported.
ilonatommy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.ComponentModel; | ||
| using System.ComponentModel.DataAnnotations; | ||
| using System.Linq.Expressions; | ||
| using System.Reflection; | ||
| using Microsoft.AspNetCore.Components.Rendering; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Forms; | ||
|
|
||
| /// <summary> | ||
| /// Displays the display name for a specified field, reading from <see cref="DisplayAttribute"/> | ||
| /// or <see cref="DisplayNameAttribute"/> if present, or falling back to the property name. | ||
| /// </summary> | ||
| /// <typeparam name="TValue">The type of the field.</typeparam> | ||
| public class DisplayNameLabel<TValue> : ComponentBase | ||
| { | ||
| private Expression<Func<TValue>>? _previousFieldAccessor; | ||
| private string? _displayName; | ||
|
|
||
| /// <summary> | ||
| /// Gets or sets a collection of additional attributes that will be applied to the created element. | ||
| /// </summary> | ||
| [Parameter(CaptureUnmatchedValues = true)] | ||
| public IReadOnlyDictionary<string, object>? AdditionalAttributes { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// Specifies the field for which the display name should be shown. | ||
| /// </summary> | ||
| [Parameter, EditorRequired] | ||
| public Expression<Func<TValue>>? For { get; set; } | ||
|
|
||
| /// <inheritdoc /> | ||
| protected override void OnParametersSet() | ||
| { | ||
| if (For == null) | ||
ilonatommy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| throw new InvalidOperationException($"{GetType()} requires a value for the " + | ||
| $"{nameof(For)} parameter."); | ||
| } | ||
|
|
||
| if (For != _previousFieldAccessor) | ||
| { | ||
| _displayName = GetDisplayName(For); | ||
| _previousFieldAccessor = For; | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| protected override void BuildRenderTree(RenderTreeBuilder builder) | ||
| { | ||
| builder.AddContent(0, _displayName); | ||
| } | ||
|
|
||
| private static string GetDisplayName(Expression<Func<TValue>> expression) | ||
| { | ||
| if (expression.Body is MemberExpression memberExpression) | ||
| { | ||
| var member = memberExpression.Member; | ||
|
|
||
| var displayAttribute = member.GetCustomAttribute<DisplayAttribute>(); | ||
| if (displayAttribute?.Name != null) | ||
| { | ||
| return displayAttribute.Name; | ||
ilonatommy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| var displayNameAttribute = member.GetCustomAttribute<DisplayNameAttribute>(); | ||
| if (displayNameAttribute?.DisplayName != null) | ||
ilonatommy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
ilonatommy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| return displayNameAttribute.DisplayName; | ||
| } | ||
|
|
||
| return member.Name; | ||
| } | ||
|
|
||
| return string.Empty; | ||
ilonatommy marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.ComponentModel; | ||
| using System.ComponentModel.DataAnnotations; | ||
| using Microsoft.AspNetCore.Components.Rendering; | ||
| using Microsoft.AspNetCore.Components.Test.Helpers; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Forms; | ||
|
|
||
| public class DisplayNameLabelTest | ||
| { | ||
| [Fact] | ||
| public async Task ThrowsIfNoForParameterProvided() | ||
| { | ||
| // Arrange | ||
| var rootComponent = new TestHostComponent | ||
| { | ||
| InnerContent = builder => | ||
| { | ||
| builder.OpenComponent<DisplayNameLabel<string>>(0); | ||
| builder.CloseComponent(); | ||
| } | ||
| }; | ||
|
|
||
| var testRenderer = new TestRenderer(); | ||
| var componentId = testRenderer.AssignRootComponentId(rootComponent); | ||
|
|
||
| // Act & Assert | ||
| var ex = await Assert.ThrowsAsync<InvalidOperationException>( | ||
| async () => await testRenderer.RenderRootComponentAsync(componentId)); | ||
| Assert.Contains("For", ex.Message); | ||
| Assert.Contains("parameter", ex.Message); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DisplaysPropertyNameWhenNoAttributePresent() | ||
| { | ||
| // Arrange | ||
| var model = new TestModel(); | ||
| var rootComponent = new TestHostComponent | ||
| { | ||
| InnerContent = builder => | ||
| { | ||
| builder.OpenComponent<DisplayNameLabel<string>>(0); | ||
| builder.AddComponentParameter(1, "For", (System.Linq.Expressions.Expression<Func<string>>)(() => model.PlainProperty)); | ||
| builder.CloseComponent(); | ||
| } | ||
| }; | ||
|
|
||
| // Act | ||
| var output = await RenderAndGetOutput(rootComponent); | ||
|
|
||
| // Assert | ||
| Assert.Equal("PlainProperty", output); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DisplaysDisplayAttributeName() | ||
| { | ||
| // Arrange | ||
| var model = new TestModel(); | ||
| var rootComponent = new TestHostComponent | ||
| { | ||
| InnerContent = builder => | ||
| { | ||
| builder.OpenComponent<DisplayNameLabel<string>>(0); | ||
| builder.AddComponentParameter(1, "For", (System.Linq.Expressions.Expression<Func<string>>)(() => model.PropertyWithDisplayAttribute)); | ||
| builder.CloseComponent(); | ||
| } | ||
| }; | ||
|
|
||
| // Act | ||
| var output = await RenderAndGetOutput(rootComponent); | ||
|
|
||
| // Assert | ||
| Assert.Equal("Custom Display Name", output); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DisplaysDisplayNameAttributeName() | ||
| { | ||
| // Arrange | ||
| var model = new TestModel(); | ||
| var rootComponent = new TestHostComponent | ||
| { | ||
| InnerContent = builder => | ||
| { | ||
| builder.OpenComponent<DisplayNameLabel<string>>(0); | ||
| builder.AddComponentParameter(1, "For", (System.Linq.Expressions.Expression<Func<string>>)(() => model.PropertyWithDisplayNameAttribute)); | ||
| builder.CloseComponent(); | ||
| } | ||
| }; | ||
|
|
||
| // Act | ||
| var output = await RenderAndGetOutput(rootComponent); | ||
|
|
||
| // Assert | ||
| Assert.Equal("Custom DisplayName", output); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task DisplayAttributeTakesPrecedenceOverDisplayNameAttribute() | ||
| { | ||
| // Arrange | ||
| var model = new TestModel(); | ||
| var rootComponent = new TestHostComponent | ||
| { | ||
| InnerContent = builder => | ||
| { | ||
| builder.OpenComponent<DisplayNameLabel<string>>(0); | ||
| builder.AddComponentParameter(1, "For", (System.Linq.Expressions.Expression<Func<string>>)(() => model.PropertyWithBothAttributes)); | ||
| builder.CloseComponent(); | ||
| } | ||
| }; | ||
|
|
||
| // Act | ||
| var output = await RenderAndGetOutput(rootComponent); | ||
|
|
||
| // Assert | ||
| // DisplayAttribute should take precedence per MVC conventions | ||
| Assert.Equal("Display Takes Precedence", output); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task WorksWithDifferentPropertyTypes() | ||
| { | ||
| // Arrange | ||
| var model = new TestModel(); | ||
| var intComponent = new TestHostComponent | ||
| { | ||
| InnerContent = builder => | ||
| { | ||
| builder.OpenComponent<DisplayNameLabel<int>>(0); | ||
| builder.AddComponentParameter(1, "For", (System.Linq.Expressions.Expression<Func<int>>)(() => model.IntProperty)); | ||
| builder.CloseComponent(); | ||
| } | ||
| }; | ||
| var dateComponent = new TestHostComponent | ||
| { | ||
| InnerContent = builder => | ||
| { | ||
| builder.OpenComponent<DisplayNameLabel<DateTime>>(0); | ||
| builder.AddComponentParameter(1, "For", (System.Linq.Expressions.Expression<Func<DateTime>>)(() => model.DateProperty)); | ||
| builder.CloseComponent(); | ||
| } | ||
| }; | ||
|
|
||
| // Act | ||
| var intOutput = await RenderAndGetOutput(intComponent); | ||
| var dateOutput = await RenderAndGetOutput(dateComponent); | ||
|
|
||
| // Assert | ||
| Assert.Equal("Integer Value", intOutput); | ||
| Assert.Equal("Date Value", dateOutput); | ||
| } | ||
|
|
||
| private static async Task<string> RenderAndGetOutput(TestHostComponent rootComponent) | ||
| { | ||
| var testRenderer = new TestRenderer(); | ||
| var componentId = testRenderer.AssignRootComponentId(rootComponent); | ||
| await testRenderer.RenderRootComponentAsync(componentId); | ||
|
|
||
| var batch = testRenderer.Batches.Single(); | ||
| var displayLabelComponentFrame = batch.ReferenceFrames | ||
| .First(f => f.FrameType == RenderTree.RenderTreeFrameType.Component && | ||
| f.Component is DisplayNameLabel<string> or DisplayNameLabel<int> or DisplayNameLabel<DateTime>); | ||
|
|
||
| // Find the text content frame within the component | ||
| var textFrame = batch.ReferenceFrames | ||
| .First(f => f.FrameType == RenderTree.RenderTreeFrameType.Text); | ||
|
|
||
| return textFrame.TextContent; | ||
| } | ||
|
|
||
| private class TestHostComponent : ComponentBase | ||
| { | ||
| public RenderFragment InnerContent { get; set; } | ||
|
|
||
| protected override void BuildRenderTree(RenderTreeBuilder builder) | ||
| { | ||
| InnerContent(builder); | ||
| } | ||
| } | ||
|
|
||
| private class TestModel | ||
| { | ||
| public string PlainProperty { get; set; } = string.Empty; | ||
|
|
||
| [Display(Name = "Custom Display Name")] | ||
| public string PropertyWithDisplayAttribute { get; set; } = string.Empty; | ||
|
|
||
| [DisplayName("Custom DisplayName")] | ||
| public string PropertyWithDisplayNameAttribute { get; set; } = string.Empty; | ||
|
|
||
| [Display(Name = "Display Takes Precedence")] | ||
| [DisplayName("This Should Not Be Used")] | ||
| public string PropertyWithBothAttributes { get; set; } = string.Empty; | ||
|
|
||
| [Display(Name = "Integer Value")] | ||
| public int IntProperty { get; set; } | ||
|
|
||
| [Display(Name = "Date Value")] | ||
| public DateTime DateProperty { get; set; } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
30 changes: 30 additions & 0 deletions
30
src/Components/test/testassets/BasicTestApp/FormsTest/DisplayNameLabelComponent.razor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| @using System.ComponentModel | ||
| @using System.ComponentModel.DataAnnotations | ||
| @using Microsoft.AspNetCore.Components.Forms | ||
|
|
||
| <div> | ||
| <p id="product-name-label"><DisplayNameLabel For="@(() => _product.Name)" /></p> | ||
| <p id="price-label"><DisplayNameLabel For="@(() => _product.Price)" /></p> | ||
| <p id="stock-label"><DisplayNameLabel For="@(() => _product.StockQuantity)" /></p> | ||
| <p id="description-label"><DisplayNameLabel For="@(() => _product.Description)" /></p> | ||
| </div> | ||
|
|
||
| @code { | ||
| private Product _product = new Product(); | ||
|
|
||
| class Product | ||
| { | ||
| [Display(Name = "Product Name")] | ||
| public string Name { get; set; } = "Sample"; | ||
|
|
||
| [DisplayName("Unit Price")] | ||
| public decimal Price { get; set; } = 99.99m; | ||
|
|
||
| [Display(Name = "Stock Quantity")] | ||
| [DisplayName("Stock Amount")] // This should be ignored, Display takes precedence | ||
| public int StockQuantity { get; set; } = 100; | ||
|
|
||
| // No attributes - should fall back to property name | ||
| public string Description { get; set; } = "Test"; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.