ValidationResult Return from the IValidatableObject.Validate file is not localized

On my ASP.NET MVC3 site, I use the following as a view model:

using DataResources = Namespace.For.The.Localization.Resources.IndexViewModel;

public class IndexViewModel, IValidatableObject {

    private string _field1_check_value = "foo";
    private string _field2_check_value = "bar";

    [Required(ErrorMessageResourceName="Validation_Field1_Required", ErrorMessageResourceType=typeof(DataResources))]
    [DataType(DataType.Text)]
    public string Field1 { get; set; }

    [Required(ErrorMessageResourceName="Validation_Field2_Required", ErrorMessageResourceType=typeof(DataResources))]
    [DataType(DataType.Field2)]
    public string Field2 { get; set; }


    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (!(Field1.Equals(_field1_check_value) && Field2.Equals(_field2_check_value))) {
            string[] memberNames = { "Field1", "Field2" };
            yield return new ValidationResult(DataResources.Validation_InvalidCredentials, memberNames);
            }
        }
    }

When a site is viewed using a culture other than the standard, validation messages are Requiredproperly localized. However, the message returned by the method Validateis always in the default culture.

Is there a way to correctly localize messages IValidatableObject.Validate?

+2
source share
2 answers

, IValidatableObject.Validate , . Validate , .

, , , ModelState :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IndexViewModel viewModel) {

    if (ModelState.IsValid) {
        //Do Stuff
        return RedirectToAction("Action", "Controller");
        }
    else {
        // The original validation did not properly localize error messages coming from IValidatableObject.Validate.
        // Clearing the ModelState and forcing the validation at this point results in localized error messages.
        ModelState.Clear();
        var errors = viewModel.Validate(new ValidationContext(viewModel, null, null));
        foreach (var error in errors)
            foreach (var memberName in error.MemberNames)
                ModelState.AddModelError(memberName, error.ErrorMessage);
        }

    return View("Index", viewModel);
    }
+2

? Controller > ExecuteCore .

.

 public class BaseController : Controller
    {
        protected override void ExecuteCore()
        {
            Thread.CurrentThread.CurrentUICulture = "en-GB"; 
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");

            base.ExecuteCore();
        }
  }
+2

Source: https://habr.com/ru/post/1667526/


All Articles