2

object htmlAttributes受け取り、渡された値を (リフレクションを介して) 取得し、それらにDictionary<string, object>. 残念ながら、これは機能しませんが、InputExtensionsクラスにDictionary<string, object> htmlAttributesa をパラメーターとして受け取るオーバーロードがあります。

問題は、この辞書がかみそりエンジンのどこかで適切に処理されていないことです (私は推測します...)。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;

PS: これはこの質問のフォローアップです。

4

1 に答える 1

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);
}
于 2012-05-17T14:59:45.780 に答える