3

It appears that creating a public property (that returns an anonymous object) in your code-behind of type 'dynamic' and exposing it to your aspx page converts the variable to type 'object'. Is this correct? Anytime I try to do this I get an exception saying

'object' does not contain a definition for val1

Here is an example:

    public dynamic showMe
    {
        get
        {
            return new
            {
                val1 = 5,
                val2 = "This is val2",
                val3 = new List<int>(){1,2,3,4,5}
            };
        }
    }

On the ASPX page I have:

<h2><%= showMe.val1 %></h2>

and with this image you can see that on my aspx page it does indeed know about the properties inside the dynamic object.

Debugger on aspx page showing the contents of showMe

Does anyone know of a way to refer to properties of anonymous objects via embedded code, or is it simply not possible with the type system? Thanks.

1 Answer 1

2

The Direct Answer

Actually this issue is that Annonymous types don't have public properties, they have internal properties. An Aspx is compiled into a separate assembly so when you try to dynamically invoke it doesn't see the property is there because it's marked as internal you don't have access from where you are calling. The quickest simplest solution is to use an ExpandoObject instead of an Anonymous object.

public dynamic showMe
    {
        get
        {
            dynamic exp = new ExpandoObject();
                exp.val1 = 5,
                exp.val2 = "This is val2",
                exp.val3 = new List<int>(){1,2,3,4,5}
            return exp;
        }
    }

Just in case

Another solution if you really want to use anonymous objects is to use ImpromptuInterface you do have to declare an interface but you get static typing without creating dummy classes. It creates a lightweight proxy that forwards invocations using the dlr in the context of the original assembly it's a lot faster than reflection.

interface IMyInterface{
    int val1 {get;}
    string val2 {get;}
    IList<int>val3 {get;}
}

public IMyInterface showMe
    {
        get
        {
            return new
            {
                val1 = 5,
                val2 = "This is val2",
                val3 = new List<int>(){1,2,3,4,5}
            }.ActLike<IMyInterface>();
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.