3

ExpandoObject匿名型のオブジェクトに変換することは可能ですか?

現在HtmlHelper、HTML 属性をパラメーターとして使用できる拡張機能があります。問題は、拡張機能にもいくつかの HTML 属性を追加する必要があるため、ExpandoObject を使用して、ユーザーが htmlAttributes パラメータを使用して関数に渡す属性と属性をマージしたことです。ここで、マージされた HTML 属性を元の HtmlHelper 関数に渡す必要がありますが、ExpandoObject を送信しても何も起こりません。したがって、ExpandoObject を匿名で型指定されたオブジェクトまたは類似のものに変換する必要があると思います。提案は大歓迎です。

4

2 に答える 2

4

目標を達成するためにexpandosに対処する必要はないと思います:

public static class HtmlExtensions
{
    public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes)
    {
        var builder = new TagBuilder("div");

        // define the custom attributes. Of course this dictionary
        // could be dynamically built at runtime instead of statically
        // initialized as in my example:
        builder.MergeAttribute("data-myattribute1", "value1");
        builder.MergeAttribute("data-myattribute2", "value2");

        // now merge them with the user attributes 
        // (pass "true" if you want to overwrite existing attributes):
        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes), false);

        builder.SetInnerText("hello world");

        return new HtmlString(builder.ToString());
    }
}

また、既存のヘルパーの一部を呼び出したい場合は、単純な foreach ループで実行できます。

public static class HtmlExtensions
{
    public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes)
    {
        // define the custom attributes. Of course this dictionary
        // could be dynamically built at runtime instead of statically
        // initialized as in my example:
        var myAttributes = new Dictionary<string, object>
        {
            { "data-myattribute1", "value1" },
            { "data-myattribute2", "value2" }
        };

        var attributes = new RouteValueDictionary(htmlAttributes);
        // now merge them with the user attributes
        foreach (var item in attributes)
        {
            // remove this test if you want to overwrite existing keys
            if (!myAttributes.ContainsKey(item.Key))
            {
                myAttributes[item.Key] = item.Value;
            }
        }
        return htmlHelper.ActionLink("click me", "someaction", null, myAttributes);
    }
}
于 2012-10-04T14:12:48.233 に答える
4

ExpandoObject を匿名型のオブジェクトに変換することは可能ですか?

実行時に匿名型を自分で生成した場合のみ。

匿名型は通常、コンパイル時にコンパイラによって作成され、他の型と同様にアセンブリに焼き付けられます。それらはいかなる意味でも動的ではありません。したがって、匿名型に使用されるのと同じ種類のコードを生成するには、CodeDOM などを使用する必要があります。これは面白くありません。

ExpandoObject他の誰かが を知っている(または単に操作できる) MVC ヘルパー クラスをいくつか作成している可能性が高いと思いますIDictionary<string, object>

于 2012-10-04T14:05:27.857 に答える