Reputation: 1030
I'm using ASP.NET MVC 4 to write a web application. When I use Html.ActionLink
to create a link I can pass data-anything attributes to action link in its htmlAttributes
parameter. But I cant use data-
and I should use data_
instead. It seems that ActionLink
changes data_
to data-
. How can I do this in a custom helper? In general how can I modify htmlAttributes
passed to a helper?
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));
}
Thanks in advance.
Upvotes: 1
Views: 241
Reputation: 24212
If you have a IDictionary<string, object> htmlAttributes
parameter, you can just use "data-foo"
.
You use data_foo
when using an anonymous object. There's a function available to replace the underscore with a hyphen: HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)
Example:
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);
}
Upvotes: 3