Properly creating an ActionLink extension using htmlAttributes

I am using a custom extension for my ActionLinks. I added the data_url attribute, which is intended to be translated into the data-url attribute. This is replacing the lower border of the dash.

Here is link 1 using my custom extension:

 @Ajax.ActionLink("Add", MyRoutes.GetAdd(), new AjaxOptions() , new { data_url = Url.Action(...)}) 

Result: data_url

Here is link 2 using the ActionLink framework:

 @Ajax.ActionLink("Add 2", "x", "x", null, new AjaxOptions() , new { data_url = Url.Action(...) }) 

Result: data-url

Here is the extension, quite simple, except that the only way to pass htmlAttributes through what I know is the ToDictionaryR() extension. I suspect this is a problem, so I wonder if I should use something else. I also added this extension below.

 public static MvcHtmlString ActionLink(this AjaxHelper helper, string linkText , RouteValueDictionary routeValues, AjaxOptions ajaxOptions , object htmlAttributes = null) { return helper.ActionLink(linkText, routeValues["Action"].ToString() , routeValues["Controller"].ToString(), routeValues, ajaxOptions , (htmlAttributes == null ? null : htmlAttributes.ToDictionaryR())); } public static IDictionary<string, object> ToDictionaryR(this object obj) { return TurnObjectIntoDictionary(obj); } public static IDictionary<string, object> TurnObjectIntoDictionary(object data) { var attr = BindingFlags.Public | BindingFlags.Instance; var dict = new Dictionary<string, object>(); foreach (var property in data.GetType().GetProperties(attr)) { if (property.CanRead) { dict.Add(property.Name, property.GetValue(data, null)); } } return dict; } 

Thank you

+1
source share
1 answer

You can use the AnonymousObjectToHtmlAttributes method, which does exactly what you want and you do not need any custom extension methods:

 public static MvcHtmlString ActionLink( this AjaxHelper helper, string linkText, RouteValueDictionary routeValues, AjaxOptions ajaxOptions, object htmlAttributes = null ) { return helper.ActionLink( linkText, routeValues["Action"].ToString(), routeValues["Controller"].ToString(), routeValues, ajaxOptions, htmlAttributes == null ? null : HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes) ); } 
+3
source

Source: https://habr.com/ru/post/907573/


All Articles