简体   繁体   中英

C# use generic invoke as MVC ActionResult

I have an Action in ASP.NET MVC4 that uses a generic method:

public ActionResult Test1()
{
    return Generic<TestClass>();
}

public ActionResult Test2(string className)
{
    MethodInfo method = typeof(ConfigController).GetMethod("Generic");
    MethodInfo generic = method.MakeGenericMethod(Type.GetType(className));
    generic.Invoke(this, null);
    return null; // Generic<TestClass>();
}

public ActionResult Generic<T>() where T : new()
{
    DatabaseUtil db = new DatabaseUtil();
    ViewBag.ClassName = typeof(T).AssemblyQualifiedName;
    return View("~/Views/Config/GenericConfig.cshtml", db.SelectAll<T>());
}

Test1() works just as expected, it passes along the TestClass to the generic method and returns the view using the model of appropriate objects.

I want to take this a step further and just pass the class name as a string so that I don't need a specific action for each type I want to use.

Test2() works up to the point where I return the view. I know the invoke is working, as I hit a breakpoint in Generic<T> with the correct class type, but the return from Test2() is still what's passed back to the browser.

How can I delegate the return to the generically invoked ActionResult method?

It was right in front of me (still new to reflection):

public ActionResult Test(string className)
{
    MethodInfo method = typeof(ConfigController).GetMethod("Generic");
    MethodInfo generic = method.MakeGenericMethod(Type.GetType(className));
    ActionResult ret = (ActionResult)generic.Invoke(this, null);
    return ret; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM