Skip to content

Fix Create Property Model Name for Complex Objects #62459

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ internal void CreateModel(ModelBindingContext bindingContext)
}

var fieldName = property.BinderModelName ?? property.PropertyName!;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
var modelName = ModelNames.CreatePropertyModelNameOptimized(bindingContext.ModelName, fieldName);
var result = await BindPropertyAsync(bindingContext, property, propertyBinder, fieldName, modelName);

if (result.IsModelSet)
Expand Down
40 changes: 40 additions & 0 deletions src/Mvc/Mvc.Core/src/ModelBinding/ModelNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,44 @@ public static string CreatePropertyModelName(string? prefix, string? propertyNam

return prefix + "." + propertyName;
}

/// <summary>
/// Create a model property name using a prefix and a property name,
/// with a small optimization to avoid redundancy.
///
/// For example, if both <paramref name="prefix"/> and <paramref name="propertyName"/> are "parameter"
/// (ignoring case), the result will be just "parameter" instead of "parameter.Parameter".
/// </summary>
/// <param name="prefix">The prefix to use.</param>
/// <param name="propertyName">The property name.</param>
/// <returns>The property model name.</returns>
public static string CreatePropertyModelNameOptimized(string? prefix, string? propertyName)
{
if (string.IsNullOrEmpty(prefix))
{
return propertyName ?? string.Empty;
}

if (string.IsNullOrEmpty(propertyName))
{
return prefix ?? string.Empty;
}

if (propertyName.StartsWith('['))
{
// The propertyName might represent an indexer access, in which case combining
// with a 'dot' would be invalid. This case occurs only when called from ValidationVisitor.
return prefix + propertyName;
}

if (string.Equals(prefix, propertyName, StringComparison.OrdinalIgnoreCase))
{
// if we are dealing with with something like:
// prefix = parameter and propertyName = parameter
// it should fallback to the property name.
return propertyName;
}

return prefix + "." + propertyName;
}
}
1 change: 1 addition & 0 deletions src/Mvc/Mvc.Core/src/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ Microsoft.AspNetCore.Mvc.ProducesDefaultResponseTypeAttribute.Description.get ->
Microsoft.AspNetCore.Mvc.ProducesDefaultResponseTypeAttribute.Description.set -> void
Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute.Description.get -> string?
Microsoft.AspNetCore.Mvc.ProducesResponseTypeAttribute.Description.set -> void
static Microsoft.AspNetCore.Mvc.ModelBinding.ModelNames.CreatePropertyModelNameOptimized(string? prefix, string? propertyName) -> string!
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,74 @@ public async Task CollectionModelBinder_BindsListOfComplexType_WithRequiredPrope
Assert.Equal("A value for the 'Name' parameter or property was not provided.", error.ErrorMessage);
}

class TestClass
{
public TestClass2 Parameter { get; set; }
}

class TestClass2
{
public string Parameter { get; set; } = "";
}

[Fact(Skip = "Nested properties are more complex to deal with it. See https://github.com/dotnet/aspnetcore/pull/62459 for more info.")]
public async Task CollectionModelBinder_CanBind_NestedProperties_WithSameNameOfParameter()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "parameter",
ParameterType = typeof(TestClass)
};

var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = new QueryString("?parameter.parameter=testing");
});

var modelState = testContext.ModelState;

// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

// Assert
Assert.True(modelBindingResult.IsModelSet);

var model = Assert.IsType<TestClass>(modelBindingResult.Model);
Assert.Equal("testing", model.Parameter.Parameter);
Assert.True(modelState.IsValid);
}

[Fact]
public async Task CollectionModelBinder_CanBind_SimpleProperties_WithSameNameOfParameter()
{
// Arrange
var parameterBinder = ModelBindingTestHelper.GetParameterBinder();
var parameter = new ParameterDescriptor()
{
Name = "parameter",
ParameterType = typeof(TestClass2)
};

var testContext = ModelBindingTestHelper.GetTestContext(request =>
{
request.QueryString = new QueryString("?parameter=testing");
});

var modelState = testContext.ModelState;

// Act
var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

// Assert
Assert.True(modelBindingResult.IsModelSet);

var model = Assert.IsType<TestClass2>(modelBindingResult.Model);
Assert.Equal("testing", model.Parameter);
Assert.True(modelState.IsValid);
}

[Fact]
public async Task CollectionModelBinder_BindsListOfComplexType_WithRequiredProperty_WithExplicitPrefix_PartialData()
{
Expand Down
Loading