aikeru
aikeru

Reputation: 3983

Asp.net WebForms Error with Anonymous Types

Please help me! I am experiencing an odd problem with anonymous types in Asp.net/WebForms using Visual Studio 2008. In the page markup, this generates a "Type Expected" error (just an example):

<%=new { property = "somevalue" }.ToString() %> 

Or even

<%var x = new { property = "somevalue" }; 
Response.Write(x.ToString()); %>

If I put this in a method, this works fine:

<%=ShowIt() %> 

...in codebehind...

public string ShowIt() 
{ return new { property = "somevalue" }.ToString(); } 

What can I do to get Web Forms to recognize anonymous type/syntax?
I tried Google.

PLEASE NOTE: I am aware that the above code is not good practice. I can't seem to use anonymous types AT ALL in markup in this project. IE: even passing as an argument:

<%=ShowIt(new { prop1 = "a", prop2 = 2 }) %> 

Does not seem to work.

Upvotes: 2

Views: 570

Answers (2)

aikeru
aikeru

Reputation: 3983

I discovered the problem in the web.config. Apparently it was missing a reference to the C# compiler under the "compilers" tag which is under the "system.codedom" tag.

      <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
        <providerOption name="CompilerVersion" value="v3.5"/>
        <providerOption name="WarnAsError" value="false"/>
      </compiler>

Upvotes: 0

jdavies
jdavies

Reputation: 12894

For me, the following:

<%= new { property = "somevalue" }.ToString() %> 

outputs the structure of the anonymous type:

{ property = somevalue }

Are you attempting to output the value of "property"?

If so use the following:

<%= new { property = "somevalue" }.property.ToString() %> 

Either way, as Smudge202 states above, you should really use a code behind method as you can make your mark-up self documenting with a good method name.

Upvotes: 3

Related Questions