简体   繁体   中英

Asp.net mvc: an object reference is required Error while calling a function in [Required(ErrorMessage)

I am creating a web app in asp.net-mvc in which I am sending a Required ErrorMessage from my model, but the problem is, I want to translate the message as per user's preference,

so I did something like below

[Required(ErrorMessage = convertErrorMessage("Text to translate"))]
public string Reviews { get; set; }

public string convertErrorMessage(string text)
{
   //convertingText in different language
   return convertedText;
}

but I am getting the below error

an object reference is required for non static field

on the below line

[Required(ErrorMessage = convertErrorMessage("Text to translate"))]

what can I do, if I want to achieve this?

You cannot call methods to initialize attributes, because these values have to be known at compile time. There are two possible other ways though:

  1. ASP.NET MVC supports standard ways to doing localization, which is the recommended way to go. It is a very broad topic, so I can only leave a few links [1] , [2] here. Notice that even the RequiredAttribute you are using has properties ErrorMessageResourceName and ErrorMessageResourceType - these are strong hints that you should be using standard tooling for standard tasks.

  2. If you still want to stick to what you have, define your own attribute and implement your custom logic in there:

     class RequiredLocalizedAttribute : RequiredAttribute { // override ErrorMessage get // or ErrorMessageString get } 

    However, I would strongly advise looking into option 1 instead. You may need a bit more time to learn and implement this, and that won't be time wasted, and may save you lots of headache as you application grows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM