修改传递给自定义HtmlHelper扩展的HTML属性

时间:2012-05-17 14:34:32

标签: c# asp.net-mvc-3 razor html-helper

我正在尝试创建一个自定义HTML帮助器扩展方法,该方法接受object htmlAttributes然后获取传入的值(通过反射)并将它们添加到Dictionary<string, object>中。不幸的是,尽管InputExtensions类中存在以Dictionary<string, object> htmlAttributes作为参数的重载,但这不起作用。

问题是这个词典没有在剃刀引擎内部正确处理(我想......)。以下是以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.

的后续行动

1 个答案:

答案 0 :(得分:2)

您应该能够直接调用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);
}