对来自Custom InputSelect的Blazor Validation消息使用Model Display名称



正如我们所知,Blazor不支持为<InputSelect>选择Int选项(但支持字符串和枚举(,我们得到以下错误消息:

错误:System.InvalidOperationException:Microsoft.AspNetCore.Components.Forms.InputSelect1[System.Nullable1[System.Int32]]不支持类型"System.Nullable `1[System.Int32]"。

因此,我编写了一个<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);
}
}
}

我有以下型号:

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; }
}

以下Blazor页面:

<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>

一切都很好。我可以在选项列表中使用int值。但是,验证错误生成为字段名称,而不是显示名称。所以我得到了";LegalEntityId字段为必填字段"而不是";法律实体字段为必填字段;。

从代码的第一个快照生成消息:

validationErrorMessage = $"The {FieldIdentifier.FieldName} field is Required.";

如何显示模型显示名称而不是字段名称?

您的CustomInputSelect继承自InputSelectInputSelect继承自InputBase。这个抽象类有一个名为DisplayName的属性。

它应该通过在剃刀文件中手动设置或通过视图模型上的Display属性来填充。

<InputDate @bind-Value="@moveOutViewModel.MoveOutDate" DisplayName="@localize["moveout_step_date_legend"]" />

[Display(Name = "address_street", ResourceType = typeof(Translations))]
public string Street { get; set; }

在您的自定义选择类中,您可以使用以下代码:

if (int.TryParse(value, out var resultInt))
{
result = (TValue)(object)resultInt;
validationErrorMessage = null;
return true;
}
else
{
result = default;
validationErrorMessage = $"The '{this.DisplayName ?? this.FieldIdentifier.FieldName}' field is required.";
return false;
}

相关内容

最新更新