Created
March 8, 2013 21:37
-
-
Save JonCanning/5120091 to your computer and use it in GitHub Desktop.
ChildModelBindingPlugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChildModelBindingPlugin : IPlugin | |
{ | |
public void Register(IAppHost appHost) | |
{ | |
appHost.RequestFilters.Add(RequestFilter); | |
} | |
static void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto) | |
{ | |
requestDto = Bind(requestDto, req.FormData); | |
} | |
static T Bind<T>(T requestDto, NameValueCollection formData) | |
{ | |
var propertyGroups = formData.AllKeys.Where(x => x.Contains('.') && formData[x].IsNotNullOrWhiteSpace()).GroupBy(x => x.Substring(0, x.IndexOf('.'))); | |
foreach (var group in propertyGroups) | |
{ | |
var propertyName = group.Key; | |
var dictionary = formData.AllKeys.Where(x => x.StartsWith(propertyName)).ToDictionary(x => x.Substring(propertyName.Length + 1), x => formData[x]); | |
var requestType = requestDto.GetType(); | |
if (requestType.GetProperties().All(x => x.Name != propertyName)) | |
continue; | |
var propertyValue = KeyValueDataContractDeserializer.Instance.Parse(dictionary, requestType.GetProperty(propertyName).PropertyType); | |
requestDto.SetProperty(propertyName, propertyValue); | |
} | |
return requestDto; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment