Reputation: 636
I have the known problem on decimal data types and the error "The field fieldname must be a number." I'm developing a ASP.NET Web App in .NET Core 2.2 with c#.
The model extract is the following:
public DateTime? ValidTo { get; set; }
public decimal? TimeZone { get; set; }
public int? Idwfstate { get; set; }
and the cshtml extract is as follows:
<div class="form-group">
<label asp-for="item.TimeZone" class="control-label"></label>
<input asp-for="item.TimeZone" class="form-control" />
<span asp-validation-for="item.TimeZone" class="text-danger"></span>
</div>
After enabling globalization for jquery validation plugin and putting the following code in startup.cs :
var defaultCulture = new CultureInfo("us-UK");
var localizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(defaultCulture),
SupportedCultures = new List<CultureInfo> { defaultCulture },
SupportedUICultures = new List<CultureInfo> { defaultCulture }
};
app.UseRequestLocalization(localizationOptions);
the problem persist.
Any suggestions? Thanks.
Upvotes: 0
Views: 1599
Reputation: 12705
If you want to localize ASP.NET Core Model Binding Error Messages ,follow these steps :
Create Resource File - Create a resource file under Resources
folder
in your solution and name the file ModelBindingMessages.fa.resx
.
Add Resource Keys - Open the resource file and add keys and values
which you want to use for localizing error messages. I used keys and
values like below image:
Configure Options - In ConfigureServices
method, when adding Mvc
, configure its options to set message accessors for ModelBindingMessageProvider
:
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => { options.ResourcesPath = "Resources";});
services.AddMvc(options =>
{
var F = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var L = F.Create("ModelBindingMessages", "RazorPages2_2Test");
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor(
(x) => L["The value '{0}' is invalid."]);
options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor (
(x) => L["The field {0} must be a number."]);
} )
.AddDataAnnotationsLocalization()
.AddViewLocalization()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
The current culture on a request is set in the localization Middleware. The localization middleware is enabled in the Startup.Configure
method. The localization middleware must be configured before any middleware which might check the request culture (for example, app.UseMvcWithDefaultRoute()
).
var supportedCultures = new[] { new CultureInfo("en"), new CultureInfo("fa") };
app.UseRequestLocalization(new RequestLocalizationOptions()
{
DefaultRequestCulture = new RequestCulture(new CultureInfo("en")),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
Reference :
https://stackoverflow.com/a/41669552/10201850
Upvotes: 2