我试图在kendo的日期时间选择器的扩展方法中添加html属性
public static DatePickerBuilder Readonly(this DatePickerBuilder builder, bool isReadOnly)
{
if (isReadOnly)
{
var dic = new Dictionary<string, object>();
dic.Add("readonly", "readonly");
builder.HtmlAttributes(dic);
}
return builder;
}
上面的代码正在运行。但它不必要的创建字典。 HtmlAttribute
方法以object
为参数,如何使用它,以便我不必创建字典?
注意:我不想使用razor语法添加readonly属性
更新1
所以我通过更改下面的代码解决了上述问题
public static DatePickerBuilder Readonly(this DatePickerBuilder builder, bool isReadOnly)
{
if (isReadOnly)
{
var comp = builder.ToComponent();
comp.HtmlAttributes.Add("readonly", "readonly");
}
return builder;
}
但是我必须确保在razor中我将readonly()
扩展方法称为链中的最后一个方法。
代码打击不起作用
@(Html.Kendo().DatePickerFor(x => x.Deadline)
.Format("MM/dd/yyyy")
.Readonly(Model.IsEnabled)
.HtmlAttributes(new { data_inherit_value = Model.InheritDeadline }))
我认为这与剑道日期选择器控制有关。它会覆盖现有的htmlattributes
如果我更改了订单并在最后使用readonly,则代码打击工作。
@(Html.Kendo().DatePickerFor(x => x.Deadline)
.Format("MM/dd/yyyy")
.HtmlAttributes(new { data_inherit_value = Model.InheritDeadline })
.Readonly(Model.IsEnabled))
答案 0 :(得分:1)
他们实际上清除 HtmlAttributes集合,然后合并,现在已清除,HtmlAttributes集合以及您传入的任何属性。我把它称为一个错误......
/// <summary>Sets the HTML attributes.</summary>
/// <param name="attributes">The HTML attributes.</param>
/// <returns></returns>
public virtual TBuilder HtmlAttributes(object attributes)
{
return this.HtmlAttributes(attributes.ToDictionary());
}
/// <summary>Sets the HTML attributes.</summary>
/// <param name="attributes">The HTML attributes.</param>
/// <returns></returns>
public virtual TBuilder HtmlAttributes(IDictionary<string, object> attributes)
{
this.Component.HtmlAttributes.Clear();
Kendo.Mvc.Extensions.DictionaryExtensions.Merge(this.Component.HtmlAttributes, attributes);
return this as TBuilder;
}
解决此问题的一种方法是为您正在使用的每个控件创建一个MergeHtmlAttributes扩展:
public static TextBoxBuilder<T> MergeHtmlAttributes<T>(this TextBoxBuilder<T> builder, object attributes)
{
Kendo.Mvc.Extensions.DictionaryExtensions.Merge(builder.ToComponent().HtmlAttributes, attributes);
return builder;
}
...并在您看来:
@(Html.Kendo().TextBoxFor(m => m.FirstName)
.Enable(Model.IsViewEditable)
.MergeHtmlAttributes(new {@class = "k-textbox"}))
答案 1 :(得分:0)
考虑这个,为了不累积多个readonlies
public static DropDownListBuilder Readonly(this DropDownListBuilder builder, bool isReadOnly)
{
const string Readonly = "readonly";
var comp = builder.ToComponent();
comp.HtmlAttributes.Remove(Readonly);
if (isReadOnly)
comp.HtmlAttributes.Add(Readonly, isReadOnly);
return builder;
}