c#-4.0 - 将 ExpandoObject 转换为匿名类型

标签 c#-4.0 asp.net-mvc-4 expandoobject

是否可以将 ExpandoObject 转换为匿名类型对象?

目前我有 HtmlHelper 扩展,可以将 HTML 属性作为参数。问题是我的扩展还需要添加一些 HTML 属性,因此我使用 ExpandoObject 来合并我的属性和用户使用 htmlAttributes 参数传递给函数的属性。现在我需要将合并的 HTML 属性传递给原始 HtmlHelper 函数,当我发送 ExpandoObject 时,没有任何反应。所以我想我需要将 ExpandoObject 转换为匿名类型对象或类似的东西 - 欢迎任何建议。

最佳答案

我认为您不需要处理 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);
    }
}

关于c#-4.0 - 将 ExpandoObject 转换为匿名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12729040/

相关文章:

c# - C#4.0中如何调用动态类型的静态方法?

c# - 3 层 asp.net mvc 应用程序中的依赖注入(inject)

wpf - 如何在 WPF DataGrid 中动态生成列?

c# - 使用点符号或索引访问 DynamicModel.Query

c#-4.0 - 如何从 Gmail 获取电子邮件

c# - SQL 连接已打开但未在此处读取

c# - 如何从 C# 中的 url 获取子字符串或字符串的一部分

asp.net-mvc-4 - MVC 4 : Durandal bundling cache

vb.net - 带有 Option Strict On 的 VB 中的 .NET 4.0 框架动态功能?

c# - WCF 集合数据契约