3

I'm trying to build the c# approximation of a JavaScript object literal to be passed to a view model in asp.net MVC:

var obj = new dynamic[]{
    new { name: "Id", index: "Id", width: 40, align: "left" },
    new { name: "Votes", index: "Votes", width: 40, align: "left" },
    new { name: "Title", index: "Title", width: 200, align: "left"}
};

The compiler is throwing:

"An anonymous type cannot have multiple properties with the same name"

Stab in the dark I'm guessing it can't distinguish between the which property goes with which anonymous object, I've seen a similar error using LINQ.

Is there a better way to accomplish what I'm trying to do?

EDIT: This is in VisualStudio 2010 and .net Framework 4. Bala R's Answer seems to address the problem for previous versions though.

Community
  • 1
  • 1
Graham Conzett
  • 8,344
  • 11
  • 55
  • 94
  • is this your real code that is causing error? – Priyank Apr 26 '11 at 19:48
  • Did you mean to use `:` syntax between property values instead of `symbol=value`? – Tejs Apr 26 '11 at 19:56
  • @priyank yes, but out of context, should I post the rest? @tejs yes I'm trying to mirror JavaScript object literal syntax – Graham Conzett Apr 26 '11 at 20:21
  • @tejs I changed it to the syntax Bala R posted below though. – Graham Conzett Apr 26 '11 at 20:51
  • 2
    Don't know if you are trying to do JSON serialization, if so, there are some built-in features that could help: http://encosia.com/2011/04/13/asp-net-web-services-mistake-manual-json-serialization/ – Dan Sorensen Apr 27 '11 at 06:11
  • @Dan great read, thanks for that. Unfortunately I need a JavaScript object literal and not a JSON object, and there doesn't seem to be a good clean method for serializing the former. I think I will end up using javascript serialization in the app and parse the JSON to an object on the client side, a little more work for the client but cleaner than passing the object literal as a string. – Graham Conzett Apr 27 '11 at 15:03
  • @Graham: JSON is just the serialized representation of a JavaScript object literal. JSON is exactly how you should transmit JavaScript objects if you're sending them to a browser or somewhere else with good JSON parsing/deserialization utilities. – Dave Ward Apr 27 '11 at 17:21
  • @Dave: Thanks, for stupid reasons it was initially decided not to do client side parsing of JSON which was the reason for passing the object literal as a string. Luckily, we've made the switch to parsing it normally (which should have happened from the beginning)! – Graham Conzett Apr 27 '11 at 17:50

1 Answers1

6

Can you try this?

var obj = new[]{
    new { name= "Id", index= "Id", width= 40, align= "left" },
    new { name= "Votes", index= "Votes", width= 40, align= "left" },
    new { name= "Title", index= "Title", width= 200, align= "left"}
};

and you should be able to access the anonymous class array like this

if (obj[0].align == "left")
{
   ...
}
Bala R
  • 107,317
  • 23
  • 199
  • 210