如何在剃须刀的某些情况下不显示标题属性?

时间:2012-06-20 12:26:11

标签: c# html asp.net-mvc-3 razor

我只想在某些情况下显示我的title属性。我不希望它在不满足条件时显示。现在它显示一个空的工具提示。当条件失败时,我不想要工具提示。

稍微清理了一下

<tr class=title="@(item.Cancelled ? "Cancelled" : item.Confirmed ? isBlocked? "blocked date": **no title attribute here** :"Confirm needed") ">

1 个答案:

答案 0 :(得分:3)

您可以随时执行以下色情内容:

<tr @Html.Raw(item.Cancelled ? "title=\"Cancelled\"" : item.Confirmed ? isBlocked ? "title=\"blocked date\"": "" : "title=\"Confirm needed\"")>

但我建议你编写一个自定义助手来生成这个td元素:

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

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