Pregunta

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>
¿Fue útil?

Solución

Try changing

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

To

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

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top