问题
I use a custom extension for my ActionLinks. I have added an attribute data_url
which is meant to be translated to an attribute of data-url
. This is, replacing the underscaore with a 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 framework ActionLink:
@Ajax.ActionLink("Add 2", "x", "x", null, new AjaxOptions()
, new { data_url = Url.Action(...) })
Result: data-url
Here is the extension, simple enough, except that the only way to pass the htmlAttributes through that I know of is by using the ToDictionaryR()
extension. I suspect this is the problem, so I am wondering if I should be using something else. I have supplied that extension below too.
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:
You could use the AnonymousObjectToHtmlAttributes method which does exactly what you want and you don't 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)
);
}
来源:https://stackoverflow.com/questions/9595334/correctly-making-an-actionlink-extension-with-htmlattributes