如何将匿名对象HTML属性转换为Dictionary <string,object>

Ste*_*lan 2 asp.net-mvc html-helper

我正在为RadioButtonFor提供额外的重载,并希望将键值对添加到传入的HTML属性中.

作为一个例子,我传递的内容如下:

new { id = "someID" }
Run Code Online (Sandbox Code Playgroud)

当我使用HtmlHelper.AnonymousObjectToHtmlAttributes方法似乎是我正在寻找的建议时,它产生了一个包含4个项目的字典,其中包含"Comparer","Count","Keys","Values"的键.然后我尝试使用Reflection来迭代"键"和"值"中的值,但是也无法使其工作.

基本上我想做的就是能够将htmlAttributes转换为IDictionary,添加一个项目,然后将其传递给常规的RadioButtonFor方法.

编辑:这是我真正想要做的事情.提供一个名为isDisabled的重载,以便能够设置单选按钮的禁用状态,因为这不能使用HTML属性直接轻松完成,因为disabled = false仍然会禁用被禁用的标记并禁用无线电.

public static MvcHtmlString RadioButtonFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, bool isDisabled, object htmlAttributes)
    {
        var linkAttributes = System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        Dictionary<string, object> htmlAttributesDictionary = new Dictionary<string, object>();
        foreach (var a in linkAttributes)
        {
            if (a.Key.ToLower() != "disabled")
            {
                htmlAttributesDictionary.Add(a.Key, a.Value);
            }
        }

        if (isDisabled)
        {
            htmlAttributesDictionary.Add("disabled", "disabled");
        }

        return InputExtensions.RadioButtonFor<TModel, TProperty>(htmlHelper, expression, value, htmlAttributesDictionary);
    }
Run Code Online (Sandbox Code Playgroud)

fre*_*n-m 5

看起来您可能会将AnonymousObjectToHtmlAttributes应用两次或者应用于错误的项目.

没有更多的代码,很难说

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(new { id = "someID" });
attributes.Count = 1
attributes.Keys.First() = id
Run Code Online (Sandbox Code Playgroud)

和....相比

var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(new { id = "someID" }));
attributes.Count = 3
attributes.Keys.Join = Count,Keys,Values
Run Code Online (Sandbox Code Playgroud)

在编写过载时,请确保您的参数为:object htmlAttributes对于new { }具有过载的部分IDictionary,例如:

Public static MvcHtmlString MyRadioButtonFor(..., object htmlAttributes)
{
    return MyRadioButtonFor(...., HtmlHelper.AnonymousObjectToHtmlAttrbites(htmlAttributes);
}

public static MvcHtmlString MyRadioButtonFor(..., IDictionary<string, object> htmlAttributes)
{
    htmlAttributes.Add("item", item);
    return RadioButtonFor(..., htmlAttributes);
}
Run Code Online (Sandbox Code Playgroud)

(只是为了清楚,永远不要使用我的... - 它只是为了说明)