0

Can anyone explain how ASP.NET MVC framework retrieve values from anonymous type parameters, such as Html.ActionLink where the parameter representing HTML attributes can be passed in as Anonymous type. I read it uses Reflection internally. I am looking for pseudocode or example to understand better.

1
  • 1
    You can go through the MVC Source and see for yourself Commented Jan 20, 2012 at 6:17

1 Answer 1

2

It uses the RouteValueDictionary precious constructor which allows you to convert an anonymous object into a dictionary:

class Program
{
    static void Main()
    {
        var anon = new { foo = "foo value", bar = "bar value" };
        IDictionary<string, object> values = new RouteValueDictionary(anon);
        foreach (var item in values)
        {
            Console.WriteLine("{0}, {1}", item.Key, item.Value);
        }
    }
}

As far as the implementation is concerned you may always take a look at the ASP.NET MVC source code but here are the relevant parts:

public class RouteValueDictionary : IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable
{

    public RouteValueDictionary(object values)
    {
        this._dictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        this.AddValues(values);
    }

    private void AddValues(object values)
    {
        if (values != null)
        {
            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(values))
            {
                object obj2 = descriptor.GetValue(values);
                this.Add(descriptor.Name, obj2);
            }
        }
    }

    ...
}

As you can see it uses the TypeDescriptor.GetProperties method to retrieve all properties of the anonymous object and their values afterwards.

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.