Reputation: 1
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.
Upvotes: 0
Views: 438
Reputation: 1038730
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.
Upvotes: 2