Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Jasper van den Bergh 4 posts 84 karma points
    Oct 15, 2019 @ 07:14
    Jasper van den Bergh
    0

    Gettings translations from viewmodels

    Hello!

    I've setup our Umbraco site to use translations. This works fine in my templates. Now I'm trying to add the translations in my viewmodels. These viewmodels contain validations messages in attributes (standard MVC validation).

    My current approach in to set the key in the ErrorMessage of the property, like so:

    [Required(ErrorMessage = "MyKey")]
    public string UserName { get; set; }
    

    Then in the OnActionExecuting override method in my SurfaceController I'm replacing the keys in the ErrorMessages by the actual value of the key:

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        ModelState.Values.ToList().ForEach(e =>
        {
            var allErrorKeys = e.Errors.Select(x => x.ErrorMessage).ToArray();
            e.Errors.Clear();
            foreach (string errorKey in allErrorKeys)
            {
                var item = Services.LocalizationService.GetDictionaryItemByKey(errorKey);
                e.Errors.Add(item.Translations.ToList()[0].Value);
            }
        });
    }
    

    Although this code needs some refactoring, it works.

    But I'm not so happy with this code, it's hacky... Is there an out of the box way of translating messages in viewmodels? Any other suggestions at all?

    Thanks!

Please Sign in or register to post replies

Write your reply to:

Draft