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

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

我正在尝试创建一个自定义 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/

相关文章:

c# - 如何处理接口(interface)函数的长描述行

mysql - ASP.NET MVC View 中如何处理 IQueryables?

c# - 在 MVC3 应用程序中使用 C# 设置日期格式

c# - 以一种形式上传多个文件 MVC4

c# - 在 WinForms 应用程序中显示 List<String> 的最快方法?

c# - 此 MSBUILD 引用中版本字符串的前缀部分是什么?

c# - ActionLinks 的 MVC 动态路由值

asp.net-mvc - 将父 ID 添加到隐藏字段

javascript - 为什么我的 DropDownList 更改事件无法工作?

asp.net-mvc - 选择在 razor html.dropdownlistfor 的页面加载中选择哪个选项