Question

I have the following if-else statement in a C# method (which returns a JSON object). The else statement executes even though the condition for the if statement (language == "en") is true. Why is this? The method is called by the following line(s) of code in another file:

Ux.locale.Manager.setConfig({
        ajaxConfig : {
            method : 'GET'
        },
        language   : 'en',
        tpl        : 'getLocale.castle?language={locale}',
        type       : 'ajax'
    });

The language value is combined with the tpl value to produce the URL that calls the method (in my case: getLocale.castle?language=en).

    [return: JSONReturnBinder]
     public Locale GetLocale(string language)
     {
        if (language == "en")
        {
           Locale englishLang = new Locale();
           englishLang.region.center.title = "Center Region";
           englishLang.region.east.title = "East Region - Form";
           englishLang.buttons.save = "Save";
           englishLang.fields.labels.firstName = "First Name";
           englishLang.fields.labels.lastName = "Last Name";
           englishLang.fields.labels.chooseLocale = "Choose Your Locale";       
           return englishLang;
       } else {
            Locale frenchLang = new Locale();
            frenchLang.region.center.title = "Region Centre";
            frenchLang.region.east.title = "Region Est - Formulaire";
            frenchLang.buttons.save = "Enregistrer";
            frenchLang.fields.labels.firstName = "Prenom";
            frenchLang.fields.labels.lastName = "Nom";
            frenchLang.fields.labels.chooseLocale = "Choisissez vos paramètres régionaux";
            return frenchLang; 
       }
}

I have tried using if (language.Equals("en")) but even then the else statement executes and not the if statement.

Was it helpful?

Solution 2

The problem was that the variable language was used twice (once in language property in the line language : 'en' and a second time in the line tpl: 'getLocale.castle?language={locale}'. This caused confusion when the language parameter was passed to the getLocale method (the correct language parameter was not being passed). When I changed the name of the language parameter, the problem was solved and the if-statement was executed.

OTHER TIPS

The else statement executes even though the condition for the if statement (language == "en") is true. Why is this?

Most likely cause? language does not equal "en". Make sure you don't have any extra whitespace in your variable (common pitfall and can sometimes be unapparent to the human eye when inspecting the debugger) and check the casing is correct.

For example, try

language.Trim().ToLower() == "en"

and chances are your problem will dissappear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top