正确地作出ActionLink的延伸与htmlAttributes [英] Correctly making an ActionLink extension with htmlAttributes
问题描述
我用我的ActionLinks自定义扩展。我已经添加的属性 data_url
其目的是要被翻译成数据网址
的属性。这是用破折号代替underscaore。
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.
下面是链接1使用我的自定义扩展:
Here is link 1 using my custom extension:
@Ajax.ActionLink("Add", MyRoutes.GetAdd(), new AjaxOptions()
, new { data_url = Url.Action(...)})
结果: data_url
下面链接2使用框架ActionLink的:
Here is link 2 using the framework ActionLink:
@Ajax.ActionLink("Add 2", "x", "x", null, new AjaxOptions()
, new { data_url = Url.Action(...) })
结果:数据网址
下面是扩展,足够简单,除了只有这样才能通过,我知道通过htmlAttributes通过使用 ToDictionaryR()
扩展。我怀疑这是问题,所以我想知道我是否应该使用别的东西。我在下面提供了过多的扩展。
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;
}
感谢您
推荐答案
您可以使用 AnonymousObjectToHtmlAttributes 方法,它不正是你想要什么,你不需要任何自定义扩展方法:
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)
);
}
这篇关于正确地作出ActionLink的延伸与htmlAttributes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!