Search code examples
asp.net-mvcmodelstateasp.net-mvc-validation

ModelState.AddModelError - How can I makeup the Resource error string


I have a ASP.NET MVC5 project where I do some input validation over more then 1 field. When an error is found I add an error to the model via :

ModelState.AddModelError("field", Resource.ErrorMessage);

The ErrorMessage in the resource file (I have several for different languages) looks like this : "{0} should be {1}"

How should I code the AddModelError to fill {0} and {1} in the ErrorMessage ?


Solution

  • Use String.Format :

    string errorMessage = String.Format(Resource.ErrorMessage,  "X",  "Y" ); 
    ModelState.AddModelError("field", errorMessage );