Monday, May 14, 2012

Conditional if in attribute in a HTML element using razor syntax.

This is little interesting. While on asp.net forum, I came across a requirement of conditional if in deciding css class of a HTML tag. I thought of writing this as a blog post.

Lets take a small section of the following code-
@for (int i = 0; i < 10; i++)
{
    if (i%2 == 0)
    {
    <div class="a">
        Test
    </div>
    }
    else
    {
    <div class="b">
        Test
    </div>
    }
}
 
In the above code segment we are simply checking the odd and even and setting the css class as "a" or "b". But the code is not optimal. We can reduce the lines of code by the following-
@for (int i = 0; i < 10; i++)
{
    <div class="@(i % 2 == 0? 'a': 'b')">
        Test
    </div>
}

No comments:

Post a Comment