Search code examples
c#.netasp.net-mvcpoasp.net-core-localization

How to pass parameter to localization string in ASP.NET core MVC .NET 6?


I am using Portable Object Localization in my ASP.NET MVC app.

I need to pass a parameter to a translation string e.g.

msgid "The {0} field is required"
msgstr[0] "موجودیت {0} لازمی میباشد"

I want to use the above example for every required field for my models.


using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace aaeamis.Models
{
    public class OrganizationModel
    {
        public int OrganizationId { get; set; }
        // I want to pass "Organization Name" to translation
        [Required(ErrorMessage = "The Organization Name field is required")]
        public string OrganizationName { get; set; }
        // I want to pass "Location" to translation
        [Required(ErrorMessage = "The Location field is required")]
        public string Location{ get; set; }
        public int CreatedBy { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.Now;
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }
}

How can I pass "Organization Name" to translation as parameter?


Solution

  • The [Required] attribute already supports parameterized error messages. In fact, the default English error message is:

    The {0} field is required.
    

    When the message is being constructed, it will then use the Name of the [Display] attribute to fill in that parameter. If you haven’t specified an explicit display name, the name of the property will be used by default.

    So the following property setup will provide an error message "The Location field is required" when the value was not set:

    [Display(Name = "Location")]
    [Required(ErrorMessage = "The {0} field is required")]
    public string Location{ get; set; }
    

    Both the text values for the Display and the Required attribute (along with other validation attributes) can be provided via ressources, so you can also generalize this for multiple languages without having to specify the actual strings in the attributes.