Comparing Boolean strings in a conditional attribute with MVC4 / Razor 2 returns unexpected results

After updating my MVC 3 MVC 4 solution using Razor 2, I ran into the following problem.

This code in view

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

returns this in MVC 3

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

and this is in MVC 4

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

which breaks my CSS.

Is this a bug introduced by the new conditional attribute function 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?

+2
css conditional attributes asp.net-mvc-4 razor-2
Nov 19 '12 at 9:38
source share
3 answers

The answer to my question or the question does not answer: https://stackoverflow.com/a/316618/

This is not a mistake, this is a new feature of Razor 2!

What happens 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 indicating the answer.

0
Nov 19 '12 at 2:35
source share

As an alternative:

 <div class="selected-@(main == "archive" ? "true" : "false")"></div> 
+2
Nov 19 '12 at 10:05
source share

Why not use this class as part of your view model, for example.

 public string MainClass { get { if(main=="archive") return "True"; return "False"; } } 

and use it in your presentation

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

Razor2 is more strict with view compilation.

+1
Nov 19
source share



All Articles