var result = (type)Activator.CreateInstance(type).Find(id);
CreateInstance(Type) returns an object which doesn't contains a Find(int) method that I believe is found on your model.
- You can't type cast via a type variable, unless it is a specified type in a generic method or generic class method.
This could be fixed by using reflexion, interface :
public JsonResult GetDetail(string modelTypeName, int id)
{
var type = Type.GetType("MyProject.WebApplication.Models.MyProjctContext." + modelTypeName);
//reflection way
var model = Activator.CreateInstance(type);
var result = (*find method return type*)type.GetMethod("Find", new Type[] { int }).Invoke(model, new object[] { id });
//constraint way : with constraint being an interface or a base class that defines .Find(int)
var result = ((*constraint*)Activator.CreateInstance(type)).Find(id);
return Json(new
{
data = result
},
JsonRequestBehavior.AllowGet);
}
or using dynamic as Marnix van Valen suggested.