ami*_*t_g 1 asp.net-mvc html-helper asp.net-mvc-3
@Html.TextBoxFor(
model => model.SomeProperty,
new { data_url = "http://www.google.com" }
)
Run Code Online (Sandbox Code Playgroud)
被渲染为
<input id="SomeProperty" data-url="http://www.google.com">
Run Code Online (Sandbox Code Playgroud)
我有一些类似于此的自定义扩展
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
{
var htmlAttrs = new RouteValueDictionary(htmlAttributes);
return TextBoxFor<TModel, TProperty>(htmlHelper, expression, htmlAttrs, disabled);
}
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes, bool disabled)
{
if (disabled)
{
htmlAttributes["disabled"] = true;
}
return htmlHelper.TextBoxFor(expression, htmlAttributes);
}
Run Code Online (Sandbox Code Playgroud)
第一过载,其中object htmlAttributes使用htmlAttributes,调用第二过载,其中htmlAttributes被转换到IDictionary<string, object> htmlAttributes和本地TextBoxFor被调用,有IDictionary<string, object>.这意味着
@Html.TextBoxFor(
model => model.SomeProperty,
new { data_url = "http://www.google.com" }, model.IsSomePropertyDisabled
)
Run Code Online (Sandbox Code Playgroud)
被渲染为
<input id="SomeProperty" data_url="http://www.google.com">
Run Code Online (Sandbox Code Playgroud)
注意data_url而不是data-url.
实质上,
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, object htmlAttributes);
Run Code Online (Sandbox Code Playgroud)
足够聪明,知道data_whatever被渲染为数据什么,而
public static MvcHtmlString TextBox(this HtmlHelper htmlHelper, string name, object value, IDictionary<string, object> htmlAttributes);
Run Code Online (Sandbox Code Playgroud)
似乎没有应用那种逻辑(或者我们可以说不够聪明).有没有办法告诉它应用相同的逻辑?
作为一种解决方法,我可以选择在我需要数据属性时不使用这些重载,并在应用disable属性时具有详细视图.还有其他方法吗?
我认为在第一个帮助器中创建时需要HtmlHelper.AnonymousObjectToHtmlAttributes方法htmlAttrs.链接方法
用指定HTML属性中的连字符( - )替换下划线字符(_).
所以,你的第一个方法应该是这样的
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
{
var htmlAttrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
return TextBoxFor<TModel, TProperty>(htmlHelper, expression, htmlAttrs, disabled);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2559 次 |
| 最近记录: |