3

I'm currently learning 2sxc and am building a directory app as my initial project.

I'm trying to use the following code in a list view to change the way an item is displayed based on the Boolean "UpgradedListing"

@foreach(var listing in AsList(Data)) {
<div @Edit.TagToolbar(listing)>
   if(listing.UpgradedListing == 'true'){
        <strong>@listing.ListingName</strong<br/>
        <a href='mailto:@listing.Email'>@listing.Email</a>
    <hr/>
    } else {
        @listing.ListingName<br/>
        <a href='mailto:@listing.Email'>@listing.Email</a>
    <hr/>
    }
</div>
}

the resulting output looks like this:

if(listing.UpgradedListing == 'true'){ Techmedics Ltd office@techmedics.co.nz
} else { Techmedics Ltd
office@techmedics.co.nz
}
if(listing.UpgradedListing == 'true'){ Solutions Online NZ Ltd enquiries@solutions-online.co.nz
} else { Solutions Online NZ Ltd
enquiries@solutions-online.co.nz
}

in other words the if else isn't being seen as code.

Can any one explain why this is?

1 Answers1

1

You just need an @ symbol in front of the first if, so

@if(listing.UpgradedListing == 'true'){

Also you've got a typo, your closing strong tag is missing its right >

And 'true' is not the same as true (boolean). 2sxc will know and return a boolean for .UpgradedListing (if you have it set AS a boolean field... if you have it as a string, then you need == "true"

and you can also move the stuff that doesn't change outside the if/else to make it more readable...

@foreach (var listing in AsList(Data))
{
    // here you can still write C# without an @
    // because it's still in code-mode
    var x = 7; // this still works here
    <div @Edit.TagToolbar(listing)>
        <!-- here Razor switches to HTML because we had a Tag around it -->
        <!-- so we need to really introduce the code-mode again -->
        @if (listing.UpgradedListing)
        {
            <strong>@listing.ListingName</strong><br />
        }
        else
        {
            @listing.ListingName<br />
        }
        <a href='mailto:@listing.Email'>@listing.Email</a>
        <hr />
    </div>
}
iJungleBoy
  • 5,325
  • 1
  • 9
  • 21
Jeremy Farrance
  • 740
  • 6
  • 11
  • I guess to add an explanation, the @ symbol is Razor's cue to switch between HTML and code. If you work with it enough and get used to it, it becomes mostly intuitive. Well, at least 99% of the time. In your above example, once the `@if(` starts it continues as code until the completion of that statement; which is the closing bracket of the else (which is part of the if()). Even though its 'in code mode' Razor is still smart enough to allow intertwined HTML (your strong and br tags). – Jeremy Farrance Mar 05 '21 at 04:17
  • Thanks Daniel, that was an awesome addition!! – Jeremy Farrance Mar 09 '21 at 22:34