2013-10-01 36 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); 
} 
相關問題