我正在尝试创建一个自定义 HTML 帮助器扩展方法,该方法采用 object htmlAttributes
然后获取传入的值(通过反射)并将其添加到 Dictionary<string, object>
中。不幸的是,尽管 InputExtensions 中存在过载,但这不起作用。需要 Dictionary<string, object> htmlAttributes
的类作为参数。
问题是该字典在 Razor 引擎内部的某个地方没有得到正确处理(我猜......)。以下是如何将其输出为 HTML:
<input name="FirstName" id="FirstName" type="text" Values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]" Keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]" Count="3" Comparer="System.Collections.Generic.GenericEqualityComparer`1[System.String]"/>
这是我的代码:
Dictionary<String, Object> attributes = new Dictionary<String, Object>();
attributes.Add("readonly", "readonly");
PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
if (propertyInfo.Name.Equals("class"))
{
attributes.Add("class", String.Format("{0} {1}", "readOnly", propertyInfo.GetValue(htmlAttributes, null)));
}
else
{
attributes.Add(propertyInfo.Name, propertyInfo.GetValue(htmlAttributes, null));
}
}
genericMethod = methodInfo.MakeGenericMethod(new[] { typeof(TModel), typeof(TProperty) });
result = genericMethod.Invoke(null, new object[] { helper, expression, (Dictionary<String, Object>)attributes }) as MvcHtmlString;
P.S:这是 this question. 的后续内容
最佳答案
您应该能够直接调用 TextBoxFor 方法并传入表达式和新的 html 属性。
public static IHtmlString Test<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
Dictionary<String, Object> attributes = new Dictionary<String, Object>();
attributes.Add("readonly", "readonly");
PropertyInfo[] properties = htmlAttributes.GetType().GetProperties();
foreach (PropertyInfo propertyInfo in properties)
{
if (propertyInfo.Name.Equals("class"))
{
attributes.Add("class", String.Format("{0} {1}", "readOnly", propertyInfo.GetValue(htmlAttributes, null)));
}
else
{
attributes.Add(propertyInfo.Name, propertyInfo.GetValue(htmlAttributes, null));
}
}
//call the input tag
return helper.TextBoxFor(expression, htmlAttributes);
}
关于c# - 修改传递给自定义 HtmlHelper 扩展的 HTML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10637782/