Skip to content

Instantly share code, notes, and snippets.

@dealproc
Last active August 29, 2015 14:04
Show Gist options
  • Save dealproc/dbabfed56df5a7931822 to your computer and use it in GitHub Desktop.
Save dealproc/dbabfed56df5a7931822 to your computer and use it in GitHub Desktop.
Binding to a generic type through reflection.
namespace Adapt.SSRV.Web.Models {
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
public class ParameterModelsModelBinder : IModelBinder {
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
if (bindingContext.ModelType != typeof(ParameterModels)) {
return false;
}
var modelData = actionContext.Request.Content.ReadAsStringAsync().Result;
var model = new ParameterModels();
var jObjectArray = JArray.Parse(modelData);
foreach (dynamic token in jObjectArray) {
string datatype = "System." + token.datatype.ToString();// +", System";
Type genType = Type.GetType(datatype);
object param = null;
if (Convert.ToBoolean(token.MultiValue.ToString())){
param = Activator.CreateInstance(typeof(MultiValueParameterModel<>).MakeGenericType(genType));
}else{
param = Activator.CreateInstance(typeof(ParameterModel<>).MakeGenericType(genType));
}
JsonConvert.PopulateObject(token.ToString(), param);
model.Add(param);
}
bindingContext.Model = model;
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment