Last active
August 29, 2015 14:04
-
-
Save dealproc/dbabfed56df5a7931822 to your computer and use it in GitHub Desktop.
Binding to a generic type through reflection.
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
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