0

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?

1
  • For example you could add a class if the user is logged and apply your style with this class like button.logged or if the class is higher .logged button Commented Aug 29, 2022 at 10:17

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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>
}

2 Comments

This works, but in doing so I should create a copy of my page, because the css class is called from almost the whole page, not from a single button as in your example
Ok, Then above answer is good in your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.