Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Mark 7 posts 28 karma points
    May 23, 2014 @ 22:10
    Mark
    0

    Simple If Statements?

    Hello i'm trying to do simple if statements in Razor but everytime i program it in a way that you would in C#, it keeps throwing errors. How can i get something like this to work:

    @foreach (DynamicNode page in pages)
     {

           string[] tags = @page.GetPropertyValue("tags").ToString().Split(',');
           string lastItem = @tags[@tags.Length - 1];
               
            <text>Tags:
             @foreach (string tag in tags)
              {  
                    if (@tag != @lastItem)
                          <text>@tag, </text>
                    else
                         <text>@tag </text>

               }
             </text>

    }

    It does not seem to like the if statement, even if you wrap it in a tag and use @ it still doesn't seem to like the idea of comparing one string to another.

    Regards,
    Mark

  • Mark 7 posts 28 karma points
    May 23, 2014 @ 22:14
    Mark
    0

    Ok... just noticed that if i wrap it the if statement in braces... that seems to make it work :|

  • Jan Skovgaard 11280 posts 23678 karma points MVP 11x admin c-trib
    May 24, 2014 @ 11:53
    Jan Skovgaard
    1

    Hi Mark

    Yup, since that's the way an if statement should look like in C# :) For others who may come across this the if statement from above should look like this

    if (@tag != @lastItem) {
             <text>@tag, </text>
    } else {
             <text>@tag </text>
    }
    

    Cheers, Jan

  • Mark 7 posts 28 karma points
    May 24, 2014 @ 17:04
    Mark
    0

    Hey Jan,

    Yeah it should look like that and always best practice to use the braces in an if statement but I tend not to use them to reduce lines in my code... I guess i just thought the syntax for both Razor and C# were alike but i'm starting to find more differences as I continue to use it.

    Regards,
    Mark

  • Jeavon Leopold 3074 posts 13632 karma points MVP 11x admin c-trib
    May 25, 2014 @ 00:37
    Jeavon Leopold
    0

    Although in this case it will work, it's not generally a good idea to have those @ in your code block and can cause you issues.

    e.g.

    if (tag != lastItem) {
        <text>@tag, </text>
    } else {
        <text>@tag </text>
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft