0

How can I dynamically change css classes i.e. seperate css classes for warning or error message and success message.

Controller Block

public ActionResult Register(string username, string name, string role, string password)
{
    int role_ = Convert.ToInt32(role);
    ObjectParameter output = new ObjectParameter("V_OUT", typeof(int));
    var result = db.P_SET_USER(username, name, role_, password, output);
    ViewBag.alert = true;
    ViewBag.StudentsCount = Convert.ToInt32(output.Value);
    return View();
}

View Block

@if (ViewBag.alert == true)
{
    <div class='callout callout-info'>
        @ViewBag.StudentsCount;
    </div>
}

I want to dynamically change the css classes for error message using div class="callout callout-danger" and for success message div class="callout callout-info".

3 Answers 3

1

You can do this, declare a variable and create the condition on it:

 @{
    var value = ViewBag.alert == true ? "callout callout-info" : "callout callout-danger;"
  }

Then call the name of the class inside it, you can just call this variable name on all your elements that need this class.

<div class='@value'>
    @ViewBag.StudentsCount;
</div>
Sign up to request clarification or add additional context in comments.

Comments

0

you can include conditions with ternary operator ?with in css class like below

<div class='@ViewBag.alert == true ? "callout callout-info" : "callout callout-danger;'>
        @ViewBag.StudentsCount;
    </div>

Comments

0

You could make different conditions for each kind of message you want to display, and apply the CSS classes to each one of them. Also, prefer TempData to ViewBag since ViewBags lose their value after redirects.

For example,
callout-info for TempData["alert"] == true,
callout-warning for TempData["alert"] == false,
callout-success for TempData["error"] == false and
callout-danger for TempData["error"] == true

1 Comment

That's the easiest way I can see you doing this, yes. Whatever color, font weight or other properties you want to change for each one of them will be easier to apply if each have its own separate CSS class. Then you make the decision in the View of which class will be applied according to the value provided by the controller.

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.