Skip to content
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions src/Components/Web/src/Forms/DisplayName.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// 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 DisplayName<TValue> : ComponentBase
{
private Expression<Func<TValue>>? _previousFieldAccessor;
private string? _displayName;

/// <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 is null)
{
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 != null)
{
var name = displayAttribute.GetName();
if (name != null)
{
return name;
}
}

var displayNameAttribute = member.GetCustomAttribute<DisplayNameAttribute>();
if (displayNameAttribute?.DisplayName is not null)
{
return displayNameAttribute.DisplayName;
}

return member.Name;
}

throw new ArgumentException(
$"The provided expression contains a {expression.Body.GetType().Name} which is not supported. " +
$"{nameof(DisplayNameLabel<TValue>)} only supports simple member accessors (fields, properties) of an object.",

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Source-Build (Managed))

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux x64)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux Musl ARM)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux Musl ARM64)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-quarantined-pr (Tests: Ubuntu x64)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Test: Ubuntu x64)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux ARM)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux ARM64)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux Musl x64)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context

Check failure on line 77 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-quarantined-pr (Tests: macOS)

src/Components/Web/src/Forms/DisplayName.cs#L77

src/Components/Web/src/Forms/DisplayName.cs(77,23): error CS0103: (NETCORE_ENGINEERING_TELEMETRY=Build) The name 'DisplayNameLabel' does not exist in the current context
nameof(expression));

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Source-Build (Managed))

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux x64)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux Musl ARM)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux Musl ARM64)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-quarantined-pr (Tests: Ubuntu x64)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Test: Ubuntu x64)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux ARM)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux ARM64)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-ci (Build Build: Linux Musl x64)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'

Check failure on line 78 in src/Components/Web/src/Forms/DisplayName.cs

View check run for this annotation

Azure Pipelines / aspnetcore-quarantined-pr (Tests: macOS)

src/Components/Web/src/Forms/DisplayName.cs#L78

src/Components/Web/src/Forms/DisplayName.cs(78,13): error CS1503: (NETCORE_ENGINEERING_TELEMETRY=Build) Argument 2: cannot convert from 'string' to 'System.Exception?'
}
}
6 changes: 6 additions & 0 deletions src/Components/Web/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,9 @@ Microsoft.AspNetCore.Components.Web.Media.MediaSource.MediaSource(byte[]! data,
Microsoft.AspNetCore.Components.Web.Media.MediaSource.MediaSource(System.IO.Stream! stream, string! mimeType, string! cacheKey) -> void
Microsoft.AspNetCore.Components.Web.Media.MediaSource.MimeType.get -> string!
Microsoft.AspNetCore.Components.Web.Media.MediaSource.Stream.get -> System.IO.Stream!
Microsoft.AspNetCore.Components.Forms.DisplayName<TValue>
Microsoft.AspNetCore.Components.Forms.DisplayName<TValue>.DisplayName() -> void
Microsoft.AspNetCore.Components.Forms.DisplayName<TValue>.For.get -> System.Linq.Expressions.Expression<System.Func<TValue>!>?
Microsoft.AspNetCore.Components.Forms.DisplayName<TValue>.For.set -> void
override Microsoft.AspNetCore.Components.Forms.DisplayName<TValue>.BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder! builder) -> void
override Microsoft.AspNetCore.Components.Forms.DisplayName<TValue>.OnParametersSet() -> void
206 changes: 206 additions & 0 deletions src/Components/Web/test/Forms/DisplayNameTest.cs
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 DisplayNameTest
{
[Fact]
public async Task ThrowsIfNoForParameterProvided()
{
// Arrange
var rootComponent = new TestHostComponent
{
InnerContent = builder =>
{
builder.OpenComponent<DisplayName<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<DisplayName<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<DisplayName<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<DisplayName<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<DisplayName<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<DisplayName<int>>(0);
builder.AddComponentParameter(1, "For", (System.Linq.Expressions.Expression<Func<int>>)(() => model.IntProperty));
builder.CloseComponent();
}
};
var dateComponent = new TestHostComponent
{
InnerContent = builder =>
{
builder.OpenComponent<DisplayName<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 DisplayName<string> or DisplayName<int> or DisplayName<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; }
}
}
22 changes: 22 additions & 0 deletions src/Components/test/E2ETest/Tests/FormsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,28 @@ public void ErrorsFromCompareAttribute()
Browser.Empty(confirmEmailValidationMessage);
}

[Fact]
public void DisplayNameReadsAttributesCorrectly()
{
var appElement = Browser.MountTestComponent<DisplayNameComponent>();

// Check that DisplayAttribute.Name is displayed
var displayNameLabel = appElement.FindElement(By.Id("product-name-label"));
Browser.Equal("Product Name", () => displayNameLabel.Text);

// Check that DisplayNameAttribute is displayed
var priceLabel = appElement.FindElement(By.Id("price-label"));
Browser.Equal("Unit Price", () => priceLabel.Text);

// Check that DisplayAttribute takes precedence over DisplayNameAttribute
var stockLabel = appElement.FindElement(By.Id("stock-label"));
Browser.Equal("Stock Quantity", () => stockLabel.Text);

// Check fallback to property name when no attributes present
var descriptionLabel = appElement.FindElement(By.Id("description-label"));
Browser.Equal("Description", () => descriptionLabel.Text);
}

[Fact]
public void InputComponentsCauseContainerToRerenderOnChange()
{
Expand Down
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"><DisplayName For="@(() => _product.Name)" /></p>
<p id="price-label"><DisplayName For="@(() => _product.Price)" /></p>
<p id="stock-label"><DisplayName For="@(() => _product.StockQuantity)" /></p>
<p id="description-label"><DisplayName 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";
}
}
1 change: 1 addition & 0 deletions src/Components/test/testassets/BasicTestApp/Index.razor
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
<option value="BasicTestApp.CustomElementsComponent">Custom elements</option>
<option value="BasicTestApp.DataDashComponent">data-* attribute rendering</option>
<option value="BasicTestApp.DispatchingComponent">Dispatching to sync context</option>
<option value="BasicTestApp.FormsTest.DisplayNameComponent">DisplayName component</option>
<option value="BasicTestApp.DuplicateAttributesComponent">Duplicate attributes</option>
<option value="BasicTestApp.DynamicComponentRendering">DynamicComponent rendering</option>
<option value="BasicTestApp.ElementFocusComponent">Element focus component</option>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@

<div class="form-floating mb-3">
<InputText @bind-Value="Input.Email" id="Input.Email" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" />
<label for="Input.Email" class="form-label">Email</label>
<label for="Input.Email" class="form-label">
<DisplayName For="() => Input.Email" />
</label>
<ValidationMessage For="() => Input.Email" class="text-danger" />
</div>
<button type="submit" class="w-100 btn btn-lg btn-primary">Reset password</button>
Expand Down Expand Up @@ -69,6 +71,7 @@
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; } = "";
}
}
Loading
Loading