1

I've

[Required]
[Display(Name ="Email")]
public string Email { get; set; }

[Required]
[Display (Name = "Password")]
public string Password { get; set; }

In my ViewModel. I'm able to localize this. Additionally, I was able to put a different localization to the 'Required' message [without specifying ResourceType and ResourceName manually] than the default Microsoft message using the resource file. How I did that? Here is the link:

https://stackoverflow.com/a/41385880/931305

Now, I want to remove the 'Name' attribute of the 'Display'. Because most of the time Display Name is always going to be the same as the actual Property name. If you notice both are 'Email'/'Password'. So it will make the code looking clean.

I was able to do this in classic ASP.NET MVC. Here is the link:

https://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx/

Now, how do I do this in .NET Core 5? I'm unable to use IValidationAttributeAdapterProvider to inject 'Display'. [I was getting all 'validation' attributes, but not Display]

Pritom Sarkar
  • 2,154
  • 3
  • 11
  • 26
Nathan
  • 137
  • 3
  • 14

2 Answers2

0

The best and standard solution is to using localization in ASP.NET Core application.

In summary, the steps to localize your application are rough as follows:

  1. Add the required localization services
  2. Configure the localization middleware and if necessary a culture provider
  3. Inject IStringLocalizer into your controllers and services to localize strings
  4. Inject IViewLocalizer into your views to localize strings in views
  5. Add resource files for non-default cultures
  6. Add a mechanism for users to choose their culture

Take a look at this article for a detailed walkthrough.

Majid Shahabfar
  • 4,010
  • 2
  • 28
  • 36
  • Sorry, I didn't ask for how to localise. I want specifically how to use Display without Name attribute – Nathan Mar 12 '21 at 04:10
0

You could write an attribute like so

public sealed class MyDisplayAttribute : DisplayNameAttribute, IModelAttribute
{
    private string _name = string.Empty;

    public MyDisplayAttribute(string displayName) 
    {
        _name= displayName;
    }

    public override string DisplayName => _name;
    public string Name => nameof(MyDisplayAttribute);
}

usage:

public class MyModel
{ 
    [MyDisplay("MyString")]
    public string MyString { get; set; }
}
Liaoo
  • 425
  • 6
  • 21
  • This means I've to use everywhere the new 'MyDisplay' instead of the usual 'Display'. However, I'm looking for way to keep on using the same 'Display'. This was possible in Classic .NET. I'm unable to 'inject/override' in .NET Core. thanks – Nathan Mar 15 '21 at 13:37