Localize `Required` annotation in French implicitly

非 Y 不嫁゛ 提交于 2019-12-04 09:39:00

In .Net Core 2, the Accessor properties in ModelBindingMessageProvider are read-only, but you can still set them by using the Set...Accessor() methods. Here's code similar to what I'm using, with thanks to the answer to ASP.NET Core Model Binding Error Messages Localization.

public static class ModelBindingConfig
{
    public static void Localize(MvcOptions opts)
    {
        opts.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor(
            x => string.Format("A value for the '{0}' property was not provided.", x)
        );

        opts.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(
            () => "A value is required."
        );
    }
}


// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddMvc(
        opts =>
        {
            ModelBindingConfig.Localize(opts);
        })
        .AddViewLocalization()
        .AddDataAnnotationsLocalization();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!