Deepesh
Deepesh

Reputation: 5604

MVC 4 Localising Validation Messages from Database

Scenario :- I am developing MVC 4 application, the website will run in several languages and will be hosted on Azure. For localizing we are relying on the database rather than resource bundle approach.

Problem :- I want to customize error messages at runtime, I want to localize the messages through the database.

I have tried to change attribute values through reflection but it had not worked.

Code :-

     //Model
      public class Home
      {
          [Required(ErrorMessage = "Hard coded error msg")]
           public string LogoutLabel { get; set; }
      } 

     //On controller
      public ActionResult Index()
    {
        Home homeData = new Home();
        foreach (PropertyInfo prop in homeData.GetType().GetProperties())
        {
            foreach (Attribute attribute in prop.GetCustomAttributes(false))
            {

               RequiredAttribute rerd = attribute as RequiredAttribute;

                if (rerd != null)
                {
                    rerd.ErrorMessage = "dynamic message";
                }
            }


        }

        return View(homeData);
    }  

On client side when validation takes place it shows me old message "Hard Coded error msg". Please suggest how this can be customised if we donot want to use Resource bundle approach

Upvotes: 2

Views: 1607

Answers (2)

Maksym Strukov
Maksym Strukov

Reputation: 2689

You would better create and register your own DataAnnotationsModelMetadataProvider where you can just override the error messages. For more detail please see the answers to the similar question here MVC Validation Error Messages not hardcoded in Attributes

Upvotes: 1

Behnam Esmaili
Behnam Esmaili

Reputation: 5967

are you intended to implement this nested loop to localize validation message of all you'r entities ? i think no.a better solution is using Validator attribute.

for you'r class :

 [Validator(typeof(HomeValidator))]
 public class Home
      {              
           public string LogoutLabel { get; set; }
      }

now lets implement HomeValidator :

public class HomeValidator : AbstractValidator<Home>
    {
        public HomeValidator()
        {
            RuleFor(x => x.LogoutLabel ).NotEmpty().WithMessage("your localized message");
        }
    }

Upvotes: 1

Related Questions