Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change div class based in property of ViewModel

I'm creating a page based in Twitter bootstrap.

In a specific CUD, I need to change a class of a div. class="tab-pane active" or class="tab-pane" depending the property of my viewmodel.

The property probably is gonna be an int, and then for every div, I will make a verification on active tab. This sounds right?

I thought in something like:

<div(@Model.ActiveTab == 1 ? class="tab-pane active" : class="tab-pane")  id="1">

but obviously this didn't work

like image 833
Custodio Avatar asked Apr 19 '12 13:04

Custodio


2 Answers

Try like this:

<div class="tab-pane @(Model.ActiveTab == 1 ? " active" : "")" id="1">
    ...
</div>

or to avoid this horrible tag soup write a custom HTML helper:

public static class TabExtensions
{
    private class TabControl: IDisposable
    {
        private readonly ViewContext _viewContext;
        public TabControl(ViewContext viewContext)
        {
            _viewContext = viewContext;
        }

        public void Dispose()
        {
            _viewContext.Writer.Write("</div>");
        }
    }

    public static IDisposable Tab(this HtmlHelper htmlHelper, bool active, object htmlAttributes)
    {
        var div = new TagBuilder("div");
        div.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        div.AddCssClass("tab-pane");
        if (active)
        {
            div.AddCssClass("active");
        }
        htmlHelper.ViewContext.Writer.Write(div.ToString(TagRenderMode.StartTag));
        return new TabControl(htmlHelper.ViewContext);
    }
}

which could be used like that:

@using (Html.Tab(Model.ActiveTab == 1, new { id = "tab1" }))
{
    ...
}

and which in this case would emit:

<div class="tab-pane active" id="tab1">
    ...
</div>
like image 170
Darin Dimitrov Avatar answered Oct 25 '22 03:10

Darin Dimitrov


This should work:

<div class="@(Model.ActiveTab == 1 ? "tab-pane active" : "tab-pane")"  id="1">
like image 42
Richard Dalton Avatar answered Oct 25 '22 04:10

Richard Dalton