Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I load an ErrorMessage on a CustomValidator from a resource file?

I would like to load the ErrorMessage for my CustomValidator from a resource file.

I have my CustomValidator set up like so:

<asp:CustomValidator ID="cv1" runat="server" ControlToValidate="txt1" 
        ErrorMessage="TEXT TO BE LOCALIZED" OnServerValidate="cv1_Validate" />

And my validation method is as follows:

protected void cv1_Validate(object source, ServerValidateEventArgs e)
{
    if (FalseCondition)
    {
        e.IsValid = false;
    }
    else
    {
        e.IsValid = true;
    }
}

The validation works correctly, but I would like to have the ErrorMessage be pulled from my local resources file.

EDIT: I'm also curious if there is any way to do this using meta:resourcekey.

like image 920
Ryan Kohn Avatar asked Aug 29 '12 14:08

Ryan Kohn


2 Answers

Assuming you have a local resource for your page (or control), this would be the way to do it

ErrorMessage="<%$ resources:ResourceName %>"

In case you get the text from a global resource file you should do something like this

ErrorMessage="<%$ resources:Strings, ResourceName %>"

Where Strings is the name of the file. This approach is called explicit localization.

EDIT

You can use meta:resourcekey. This is called implicit localization. You'll need to have local resources since this approach is not valid for global resources.

  1. Make sure that you have local resource files (.resx files) that meet the following criteria:

    • They are in an App_LocalResources folder.

    • The base name matches the page name.

    For example, if you are working with the page named Default.aspx, the resource files are named Default.aspx.resx (for the default resources), Default.aspx.es.resx, Default.aspx.es-mx.resx, and so on.

    • The resources in the file use the naming convention resourcekey."property".

    For example, key name Button1."Text".

  2. In the control markup, add an implicit localization attribute.

    For example:

    <asp:Button ID="Button1" runat="server" Text="DefaultText" meta:resourcekey="Button1" />

Source: MSDN

like image 77
Claudio Redi Avatar answered Sep 20 '22 02:09

Claudio Redi


If you want to do it in the code-behind, you can use the following:

ResourceManager resmgr = new ResourceManager("YourApplication.YourBaseResourceFile ", 
                              Assembly.GetExecutingAssembly());

protected void cv1_Validate(object source, ServerValidateEventArgs e) 
{   

if (FalseCondition)  
   {  
       CultureInfo ci = Thread.CurrentThread.CurrentCulture;    
       String str = resmgr.GetString("Error Msg Key in Resource File");
       cv1.ErrorMessage =str;      
       e.IsValid = false; 
    }     
else   
  {   
     e.IsValid = true;  
   } 
} 
like image 30
gunvant.k Avatar answered Sep 21 '22 02:09

gunvant.k