As we know Blazor doesn't support Int option select for <InputSelect> (but support string & Enum) and we get the following error message:
Error: System.InvalidOperationException: Microsoft.AspNetCore.Components.Forms.InputSelect1[System.Nullable1[System.Int32]] does not support the type 'System.Nullable`1[System.Int32]'.
Therefore, I write a <CustomInputSelect>:
public class CustomInputSelect<TValue> : InputSelect<TValue>
{
protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage)
{
if (typeof(TValue) == typeof(int?))
{
if (int.TryParse(value, out var resultInt))
{
result = (TValue)(object)resultInt;
validationErrorMessage = null;
return true;
}
else
{
result = default;
validationErrorMessage = $"The {FieldIdentifier.FieldName} field is Required.";
return false;
}
}
else
{
return base.TryParseValueFromString(value, out result, out validationErrorMessage);
}
}
}
I have the following Model:
public class Risk : ICloneable
{
/// <summary>
/// Associated Legal Entity of the risk
/// </summary>
[Required]
[Display(Name = "Legal Entity")]
public int? LegalEntityId { get; set; }
/// <summary>
/// Associated Legal Entity Short Code of the risk
/// </summary>
[Required]
[Display(Name = "Legal Entity Short Code")]
public string LegalEntityShortCode { get; set; }
}
The following Blazor page:
<CustomInputSelect id="ddlLegalEntity" class="form-control InputTextHeigth" @bind-Value="ShowRisk.LegalEntityId">
@foreach (var option in LEList)
{
<option value="@option.Id">
@option.OptionName
</option>
}
</CustomInputSelect>
<div class="cs-col-6">
<ValidationMessage class="form-control" For="@(() => ShowRisk.LegalEntityId)" />
</div>
Everything is working fine. I can use int value on Option list. However, The validation error is generating as Field name instead of Display name. So I getting "The LegalEntityId field is Required." instead of "The Legal Entity field is Required".
From the first snapshot of the code, the message is generated:
validationErrorMessage = $"The {FieldIdentifier.FieldName} field is Required.";
How can I display Model Display name instead of FieldName?