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

拟墨画扇 提交于 2019-12-11 03:18:55

问题


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?


回答1:


As alternative:

<div class="selected-@(main == "archive" ? "true" : "false")"></div>



回答2:


Why not have this class as part of your view model, e.g.

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

and use this in your view

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

Razor2 is more strict with it's view compilation.




回答3:


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.



来源:https://stackoverflow.com/questions/13451051/boolean-string-comparison-in-conditional-attribute-with-mvc4-razor-2-returns-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!