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:
<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.
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
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.
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
Ok... just noticed that if i wrap it the if statement in braces... that seems to make it work :|
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
Cheers, Jan
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
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.
is working on a reply...