anita
anita

Reputation: 193

Incorrect ternary operation in Razor

I have this div tag, which uses a ternary operation to determine whether one styling should be used or a different one should be used.

<div 
     class="@(Model.HeroBannerImageSmall ? "--imageSmall" : "--image")"
     style="@(Model.isSelected ? "background-position-x: "@Model.CropPositionX"% background-position-y: "@Model.CropPositionY"%; " : "background-position: @Model.UniformCropPosition%; ")
                 background-image: url(@Model.ContentUrl)">

</div>            

Following the styles

               var imageClass = Model.HeroBannerImageSmall ? "hero__background hero__background--imageSmall" : "hero__background hero__background--image";
                var imageStyles = Model.isSelected ? "background-position-x: Model.CropPositionX%; background-image: url(Model.ContentUrl);" : "background -position: Model.CropPosition%; background-image: url(Model.ContentUrl);";

but this does not add the model value, but just write it as a string. How do I insert the value?

Upvotes: 0

Views: 45

Answers (2)

bgraham
bgraham

Reputation: 2027

You've gotta mix and match your single and double quotes to make this work! For example:

class='@(Model.HeroBannerImageSmall ? "--imageSmall" : "--image")'

Potentially might be easier to read if you pulled it out into a code branch ahead of the div. ie:

@{
    var imageClass = Model.HeroBannerImageSmall ? "--imageSmall" : "--image";

    var imgageStyle = Model.isSelected ? 
              "background-position-x: " + Model.CropPositionX + "% background-position-y: " + Model.CropPositionY + "%;" : 
              "background-position: " + Model.UniformCropPosition + "%; ";
     imgageStyle += "background-image: url(" + Model.ContentUrl + ")";

}



class='@imageClass' style='@imageStyle'

Upvotes: 0

mallenswe
mallenswe

Reputation: 42

Try using single quote marks inside the ternary

<div
   class='@(Model.HeroBannerImageSmall ? "--imageSmall" : "--image")'
   style='@(Model.isSelected ? "background-position-x:@Model.CropPositionX" % "background-position-y:@Model.CropPositionY"&; : "background-position:@Model.UniformCropPosition"&;')
   background-image: url(@Model.ContentUrl)'>
</div>

Upvotes: 1

Related Questions