2012-10-04 104 views
2

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

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

+1

您可以显示助手的代码?它会更好地说明你的目标。我怀疑你不需要任何ExpandoObject,并且可能有其他方法来实现你的目标。 –

+0

@DarinDimitrov:是的,你是对的:)我用Dictionary :)解决了这个问题 – xx77aBs

+0

[Cast ExpandoObject to anonymous type]可能重复(http://stackoverflow.com/questions/10241776/cast- expandoobject-to-anonymous-type) – nawfal

回答

3

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

谢谢!我忘了你可以提供htmlAttributes作为字典 :) – xx77aBs

+1

是的,顺便说一下,我会建议你总是提供与RouteValueDictionary或IDictionary 一起工作的定制助手的重载。除了获取匿名对象之外,还可以使用路由值和html属性。 –

3

是否有可能将ExpandoObject转换为匿名类型的对象?

仅当您在执行时自己生成匿名类型。

匿名类型通常由编译器在编译时创建,并像任何其他类型一样烘焙到您的程序集中。它们在任何意义上都不具有动态性。所以,你必须使用CodeDOM或类似的东西来生成用于匿名类型的相同类型的代码......这不会很有趣。

我认为更有可能是别人会创建一些知道ExpandoObject(或只能与IDictionary<string, object>一起工作)的MVC帮助类。

相关问题