0

How can I write this if statement

@if (camera.IsInStock)
{
    <span class="text-success" style="float:right">IN STOCK</span>
}
else
{
    <span class="text-danger" style="float:right">OUT OF STOCK</span>
}

in expression like this:

@(camera.IsInStock ? "<span style='float:right' class='success'>IN STOCK</span>" : "<span style='float:right' class='danger'>OUT OF STOCK</span>")

The expression I provided doesn't work. Thanks

1 Answer 1

2

When you are trying to render the HTML markup inside a ternary expression, you should use Html.Raw method so that it will not get html encoded by razor.

@(camera.IsInStock ? 
        Html.Raw("<span style='float:right' class='text-success'>IN STOCK</span>") 
      : Html.Raw("<span style='float:right' class='text-danger'>OUT OF STOCK</span>"))

I personally prefer your first approach as i feel that is more readable. you may also consider creating helper methods which takes the IsInStock flag and return the css class needed and the text needed or even your entire span markup.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.