Skip to content

Instantly share code, notes, and snippets.

@JonCanning
Created March 8, 2013 21:37
Show Gist options
  • Save JonCanning/5120091 to your computer and use it in GitHub Desktop.
Save JonCanning/5120091 to your computer and use it in GitHub Desktop.
ChildModelBindingPlugin
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