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?
CodePudding user response:
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.
CodePudding user response:
First, you need to get the string "OrganizationName"
from the variable itself
var fieldName = nameof(OrganizationName)
Then, if you are on C# 10 (.NET 6.0) you can use const string interpolation to set the error message.
[Required(ErrorMessage = $"The {nameof(OrganizationName)} field is require")]
public string OrganizationName { get; set; }
[Required(ErrorMessage = $"The {nameof(Location)} field is require")]
public string Location { get; set; }
Note the $
before the string.