在自定义助手中使用数据

时间:2013-10-01 14:43:48

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

我正在使用ASP.NET MVC 4编写Web应用程序。当我使用Html.ActionLink创建链接时,我可以将数据 - 任何属性传递给其htmlAttributes参数中的操作链接。但是我无法使用data-而我应该使用data_。似乎ActionLinkdata_更改为data-。如何在自定义助手中执行此操作?一般来说,如何修改传递给助手的htmlAttributes

public static MvcHtmlString AuthorizeModalLink(this HtmlHelper Helper, string Text, object htmlAttributes)
{
    var builder = new TagBuilder("a");
    builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    return MvcHtmlString.Create(builder.ToString(TagRenderMode.StartTag) + Text + builder.ToString(TagRenderMode.EndTag));
}

提前致谢。

1 个答案:

答案 0 :(得分:3)

如果您有IDictionary<string, object> htmlAttributes参数,则可以使用"data-foo"

使用匿名对象时使用data_foo。有一个函数可以用连字符替换下划线:HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)

示例:

public static HtmlString CustomCheckboxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes)
{
    return CustomCheckboxFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}

public static HtmlString CustomCheckboxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, IDictionary<string, object> htmlAttributes)
{
    string controlHtml = htmlHelper.CheckBoxFor(expression, htmlAttributes).ToString();

    return htmlHelper.FormItem(expression, controlHtml);
}