Question

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>
Was it helpful?

Solution

Try changing

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

To

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top