Here is my controller code where I have set the value of ViewBag.Val as 1. Now based on this value i'm trying to change the class of an href in my Index view but its not setting the class to Class="A". <a @ViewBag.Val==1? class="A":class="B" href="#"> Hello </a> I'm quite new to asp.net MVC, so any help would be appreciated.

But what i get is as shown below:

<a 1="=1?" class="A" :class="B" href="#">
    Hello
</a>
有帮助吗?

解决方案

Try changing

@ViewBag.Val==1? class="A":class="B"

To

class="@(ViewBag.Val==1? "A": "B")"

其他提示

Your razor code is wrong. Look at here:

<a class=@ViewBag.Val==1? "A":"B" href="#">
   Hello
</a>

Try working with the ? conditional operator in your controller to determine the class you want in your View.

In controller:

int someInt = 1;
ViewBag.Class = someInt == 1 ? "A" : "B";

In view:

<a class="@ViewBag.Class">

Seems to be better SoC this way since you aren't bogging your View down with conditional logic.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top