mrfazolka
mrfazolka

Reputation: 790

.NET MVC - pass List of runtime type to Grid<T>

I have List<MyType> list and need to pass list to @Html.Grid((IEnumerable<MyType>)list, "MvcGrid/customGridView") in my view. MyType was created at runtime. Can you provide some example code to do this??


Concreatelly: In my controller i have this code:

public ActionResult dataRuntime()
{
            var myType = CompileResultType();
            var myObject = Activator.CreateInstance(myType);
            var myObject2 = Activator.CreateInstance(myType);

            Type listType = typeof(List<>).MakeGenericType(new Type[] { myObject.GetType() });
            IList listt = (IList)Activator.CreateInstance(listType);
            listt.Add(myObject);
            listt.Add(myObject2);

            ViewData["type"] = myType;

            return View(list);
}

So I have List<MyType> with two MyType objects. In view I have:

@{
    Type t = (Type)ViewData["type"];
    var list = Model;
}

and need to call method like this:

@Html.Grid((IEnumerable<MyType>)list, "MvcGrid/customGridView")

So I need to do something like:

@Html.Grid((IEnumerable<t>)list, "MvcGrid/customGridView")

but it doesn't work, obviously. So I tried do this:

@{
    // For non-public methods, you'll need to specify binding flags too
    System.Reflection.MethodInfo method = Html.GetType().GetMethod("Grid")
                                 .MakeGenericMethod(new Type[] { t });
    var g = method.Invoke(Html, new object[] { list, "MvcGrid/customGridView" });
}

but I get an error:

System.NullReferenceException: Object reference not set to an instance of an object

which is logic, because HtmlHelper doesn't have method Grid.

Grid class is defined here: https://github.com/leniel/Grid.Mvc/blob/master/GridMvc/Grid.cs

Do someone know, how to make it work?

Upvotes: 0

Views: 298

Answers (1)

Steves
Steves

Reputation: 3234

Grid is actually static method, so you do not pass Html as the first parameter to method.Invoke.

In case of static method, Invoke ignores the first parameter, so you can pass in just null for example. Do not forget to put Html into the parameters array:

method.Invoke(null, new object[] { Html, list, "MvcGrid/customGridView" });

Edit: and also you do not get the reference to Grid method from HtmlHelper type. Use intellisense to find out on which type is the Grid method defined and use that type instead of Html.GetType()

Upvotes: 1

Related Questions