3

I want to add more classes to a table in mvc3 c#.

I now have this:

<tr class=@(item.cancelled ? "cancelled" : "")> 

Is it possible to add an extra class here for example:

<tr class= "cancelled added">
4
  • MVC and C# have nothing to do with it, it's purely a HTML/CSS related question. AFAIK, you can't have multiple classes on an HTML element. Commented May 15, 2012 at 7:51
  • webdesign.about.com/od/css/qt/tipcssmulticlas.htm Commented May 15, 2012 at 7:53
  • @ThomasLevesque Yes you can, i do it all the time. Read the link from Oskar Commented May 15, 2012 at 8:33
  • @Sam, my mistake... last time I tried it didn't seem to work. CSS isn't really my thing ;) Commented May 15, 2012 at 9:09

2 Answers 2

4
 <tr class="@(item.cancelled ? "cancelled" : "") added"> 
Sign up to request clarification or add additional context in comments.

Comments

1

A better way to use it is like this:

@using (Html.Td(item, isBlocked))
{
    <div>some contents for the td</div>
}

like this:

public static class HtmlExtensions
{
    private class TdElement : IDisposable
    {
        private readonly ViewContext _viewContext;
        private bool _disposed;

        public TdElement(ViewContext viewContext)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException("viewContext");
            }
            _viewContext = viewContext;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                _disposed = true;
                _viewContext.Writer.Write("</td>");
            }
        }
    }

    public static IDisposable Td(this HtmlHelper html, ItemViewModel item, bool isBlocked)
    {
        var td = new TagBuilder("td");
        var title = item.Cancelled 
            ? "Cancelled" 
            : item.Confirmed 
                ? isBlocked 
                    ? "blocked date" 
                    : "" 
                : "Confirm needed";

        if (!string.IsNullOrEmpty(title))
        {
            td.Attributes["title"] = title;
        }
        html.ViewContext.Writer.Write(td.ToString(TagRenderMode.StartTag));
        var element = new TdElement(html.ViewContext);
        return element;
    }
}

2 Comments

I think I prefer Chuck's answer here. It's way shorter and easier to use. But thanks for your work.
Indeed Chuck's answer works better for you here if you plan on only adding one attribute. it could get long if you need to use a lot of attributes

Your Answer

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