2013-10-01 32 views
1

我正在使用ASP.NET MVC 4编写Web应用程序。当我使用Html.ActionLink创建链接时,我可以将htmlAttributes参数中的data-anything属性传递给动作链接。但我不能使用data-,我应该使用data_来代替。看起来ActionLink更改为data_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)); 
} 

在此先感谢。

+0

不是一个确切的重复,但[这](http://stackoverflow.com/a/11606534/729541)应该帮助你出去。 –

+0

我修改了这个问题。 – Beginner

回答

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); 
} 
相关问题