Search code examples
cssattributesasp.net-mvc-4conditional-statementsrazor-2

Boolean string comparison in conditional attribute with MVC4 / Razor 2 returns unexpected results


After upgrading my MVC 3 solution to MVC 4 with Razor 2 I came across the following problem.

This code in a view

@{
    string main = "archive";
}
    <div class="selected-@(main == "archive")"></div>

returns this in MVC 3

<div class="selected-True"></div>

and this in MVC 4

<div class="selected-class"></div>

which breaks my CSS.

Is that a bug introduced by the new conditional attribute feature in Razor 2?

My workaround is this:

<div class="selected-@((main == "archive").ToString())"></div>

which returns this:

<div class="selected-True"></div>

Does anyone have a better suggestion?


Solution

  • My bug-or-not question is answered here: https://stackoverflow.com/a/13455272/533460

    It's not a bug, it's a new feature of Razor 2!

    What is happening in my code is based on this principle

    <input checked="@ViewBag.Checked" type="checkbox"/>
    

    becomes

    <input checked="checked" type="checkbox"/>
    

    when ViewBag.Checked == true.

    So

    <div class="@(main == "archive")"></div>
    

    becomes

    <div class="class"></div>
    

    Thanks to @webdeveloper (https://stackoverflow.com/users/1667969/webdeveloper) for pointing me to the answer.