0

I have an Orders model containing a Status property. Depending on the value of Status, I'd like to set the CSS of multiple elements in the dom.

<span class = "green">ORDERED</span>
<span class = "orange">SHIPPED</span>
<span class = "gray">RECEIVED</span>

I'd like to set those green/orange/gray classes according to the value of Order.Status, within the Details view. How can I do this?

1 Answer 1

7

You could write a custom helper that will return the correct CSS based on the Status value:

public static class Htmlextensions
{
    public static string GetStatusCss(this HtmlHelper html, string status)
    {
        if (string.Equals(status, "ORDERED", StringComparison.OrdinalIgnoreCase))
        {
            return "green";
        }
        else if (string.Equals(status, "SHIPPED", StringComparison.OrdinalIgnoreCase))
        {
            return "orange";
        }
        return "gray";
    }
}

and then you could call this helper in the view to get the correct CSS class:

<span class="@Html.GetStatusCss(Model.Status)">
    @Html.DisplayFor(x => x.Status)
</span>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Where would I put this class in the project?
There's no rule. You could put it in a Helpers folder for example. Just make sure that you have brought the namespace in which this class is defined into scope in the view (either by adding a @using directive or globally by adding it to the namespaces section of the ~/Views/web.config file)

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.