2012-02-14 66 views
2

兩個目標我已經聲明,像這樣兩個對象:如何合併在C#asp.net MVC3

new {@class = "aClass", bar="bar"} 

new{foo = "foo"} 

我如何將它們結合起來,所以我得到這樣的結果?

{@class = "aClass", bar="bar", foo = "foo"} 

(以任意順序)

我的目標是額外的HTML屬性結合在一個自定義的HtmlHelper。

乾杯

+1

你能指望什麼發生,如果它們包含重複的(意思是兩個集合包含相同的屬性)? – 2012-02-14 06:25:42

+0

有沒有真的想過,因爲我不指望它發生。但這是一個很好的觀點。我想我必須重寫它。 – MrJD 2012-02-14 21:33:06

回答

3
object x = new { @class = "aClass", bar = "bar" }; 
object y = new { foo = "foo" }; 

var htmlAttributes = new RouteValueDictionary(x); 
foreach (var item in new RouteValueDictionary(y)) 
{ 
    htmlAttributes[item.Key] = item.Value; 
} 

// at this stage htmlAttributes represent an IDictionary<string, object> 
// that will contain the 3 values and which could be passed 
// along to the overloaded versions of the standard helpers 
// for example: 
var link = htmlHelper.ActionLink("link text", "foo", null, htmlAttributes); 

// would generate: 
// <a href="/home/foo" class="aClass" bar="bar" foo="foo">link text</a> 
+0

夢幻般的答案!正是我需要的。我可以查詢,如果兩個對象都包含同名的屬性會發生什麼? – MrJD 2012-02-14 22:14:33

+1

@MrJD,第二個將佔上風,並覆蓋第一個。但是,如果這不是你想要的foreach循環內的東西,你可以在覆蓋它之前測試一個鍵是否存在於htmlAttributes字典中。 – 2012-02-14 22:18:00

+0

該功能沒問題。我只是不想要拋出任何異常。謝謝! – MrJD 2012-02-14 22:19:47

0

假設兩個對象匿名類型

var a = new { @class = "aClass", bar = "bar" }; 
var b = new { foo = "foo" }; 

結合它們是創建具有兩者的成員的新對象的唯一方式:

var result = new { [email protected], a.bar, b.foo }; 

Screenshot

+0

這很好,除非我沒有第一堂課的定義。所以我不能選擇它的屬性。 – MrJD 2012-02-14 21:32:15

1

我已經試過凱爾芬利的Merge Two Objects into an Anonymous Type,它工作的很完美。

隨着TypeMerger合併很簡單,只要

var obj1 = new {foo = "foo"};

var obj2 = new {bar = "bar"};

var mergedObject = TypeMerger.MergeTypes(obj1 , obj2);

就是這樣,你得到的合併對象,除此之外,還有一項條款,忽視特定的屬性。您也可以爲MVC3使用相同的功能。