object Bind(object requestDto, NameValueCollection formData) { var propertyGroups = formData.AllKeys.Where(x => x.Contains('.')).GroupBy(x => x.Substring(0, x.IndexOf('.'))); foreach (var group in propertyGroups) { var propertyName = group.Key; var propertyInfo = requestDto.GetType().GetProperty(propertyName); var propertyType = propertyInfo.PropertyType; var bindings = new List<MemberBinding>(); foreach (var childPropertyKey in group) { var childPropertyName = childPropertyKey.Substring(childPropertyKey.IndexOf('.') + 1); var childPropertyInfo = propertyType.GetProperty(childPropertyName); var childPropertyType = childPropertyInfo.PropertyType; if (!childPropertyType.IsPrimitive) continue; var childPropertyValueString = formData[childPropertyKey]; var parseExpression = Expression.Call(childPropertyType.GetMethods().Single(x => x.Name == "Parse" && x.GetParameters().Count() == 1), Expression.Constant(childPropertyValueString)); var childPropertyValue = Expression.Lambda(parseExpression).Compile().DynamicInvoke(); bindings.Add(Expression.Bind(childPropertyInfo, Expression.Constant(childPropertyValue))); } Expression memberInit = Expression.MemberInit(Expression.New(propertyType), bindings); var propertyValue = Expression.Lambda(memberInit).Compile().DynamicInvoke(); var propertyExpression = Expression.Property(Expression.Constant(requestDto), propertyInfo); var assignExpression = Expression.Assign(propertyExpression, Expression.Constant(propertyValue)); Expression.Lambda(assignExpression, Expression.Parameter(requestDto.GetType())).Compile().DynamicInvoke(requestDto); } return requestDto; }
Model Binding using Expression Trees
New on Geeks with Blogs
- Your Customers Build the Features Now
I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.
- Get the Size of a Directory in Linux the Easy Way
du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.
- Vim Search and Replace: The Ultimate Guide
One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.
- Because of AI, You Need a New Development Team
Your existing team is buried in the complexity of your existing product. AI rewards the team with a blank slate. Most companies don't have one.
