skip to Main Content

I am working on an MVC project,
what I need is to have custom css classes to use one when there is a user logged in to the site, and the other when accessing the site as a guest.
I thought about using a function in the controller that checks if there is a logged in account and a ViewBag to pass a true / false value to the view.
What I ask myself is:

How do I create a condition so that taking this ViewBag with the true / false value can enable a css class and disable another?

2

Answers


  1. You can use the following code to apply different css using C# variable.
    Assuming you have user and guest css class created, and you want to check is user logged in through ViewBag.UserLoggedIn:

    @{
        var cssName = "";
        if (ViewBag.UserLoggedIn)
        {
            cssName = "user";
        }
        else
        {
            cssName = "guest";
        }
    }
    
    
    <div class="otherclass @cssName"> Hello </div>
    
    Login or Signup to reply.
  2. You can set the Session value when User gets logged in. And check for that Session value in View

    Controller

    Public ActionResult LogIn()
    {
        Session["User"] = your_value;
        ...
    }
    

    View

    @if(Session["User"] != null)
    {
        <p class="your_class">User Logged In</p>
    }
    else
    {
        <p class="your_class">Guest User</p>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search