如何为@ Html.DisplayFor应用CSS?

时间:2014-05-30 19:29:21

标签: css asp.net-mvc asp.net-mvc-4

我正在尝试将CS​​S应用于DisplayFor。我不能。怎么做?

 MeetingAbstract.AbstractTitleInEnglishLabel = meetingQuestionses[0].question_text

@Html.DisplayFor(model => model.AbstractTitleInEnglishLabel, new { @class = "control-label mandatory" })

如果我使用DisplayFor。它显示为没有 粗体 enter image description here

如果我使用LableFor

enter image description here

2 个答案:

答案 0 :(得分:0)

DisplayFor用作模板系统。如果你没有使用模板,你应该坚持将它包装在一些html标签中。

答案 1 :(得分:0)

该方法没有重载允许HTML属性匿名对象see the MSDN。如果您愿意,可以自己创建一个重载,或者只是在发现时使用LabelFor

但是,如果您使用LabelFor,请注意该方法的签名与所有其他扩展方法不同。第一个字符串参数始终是相应<input>元素的标识符。如果没有第二个字符串参数,它也会显示该文本,但如果存在“。”则会被截断。在你的文字中。

要解决此问题并保持对代码的一致外观,我创建了@Html.Span()扩展方法,如下所示:

/// <summary>
/// Method to create an HTML Span node.
/// </summary>
/// <param name="displayText">The Text to display as the value.</param>
/// <param name="expression">A corresponding Control that this Span is "for".</param>
/// <param name="htmlAttributes">An object that contains HTML attributes to set for this Span.</param>
/// <returns>Returns a Span element that will display the given text.</returns>
/// <remarks>Using Html.Label will take the first string parameter as the name of the input the label is "for".
/// To display text, you need to use the second string parameter, which is contrary to every other method they use.
/// This method will instead create a span tag with the appropriate text being displayed.</remarks>
public static MvcHtmlString Span(this HtmlHelper html, string displayText, string expression, object htmlAttributes) {
    TagBuilder spanBuilder = new TagBuilder("span");

    if (!string.IsNullOrEmpty(expression)) {
        spanBuilder.MergeAttribute("for", expression);
    }

    if (htmlAttributes != null) {
        RouteValueDictionary attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        foreach (KeyValuePair<string, object> attr in attributes) {
            spanBuilder.MergeAttribute(attr.Key, attr.Value.ToString());
        }
    }

    spanBuilder.SetInnerText(displayText);

    return MvcHtmlString.Create(spanBuilder.ToString(TagRenderMode.Normal));
}

对于所有调用此方法的方法,我也有一系列类似的重载(每个参数都有较少的参数)。