lundi 10 septembre 2018

GetGenericArguments()[0] vs GetGenericArguments()[1] in regards to anonymous types in c#

The Goal

I need a list view that can display any query I throw into it without having to create a custom view model or custom view.

The Solution

Using reflection, I can pass anonymous types to custom helper functions to create all headers and rows within a table.

The Problem

In order to get the anonymous type, I need to use the GetGenericArguments() method and use the [] operator to pull that info out. However, when I use a named Type (a model that I have hard-coded), the necessary index to grab that type from the IEnumerable<object> line is 0. When I use an anonymous type, the necessary index is 1. Why is this, and is there a better way I can get that Type?

The Code

Controller:

(I can pass any of these model queries to the view and the table displays accordingly)

public ActionResult Index()
{
    var models = taskService.ReadMany().Select(m => new
    {
        Name = m.Title,
        Summary = m.Details,
        Importance = m.Priority,
        DueDate = m.DateDue
    });
    var models = taskService.ReadMany();
    var models = taskService.ReadMany().GroupBy(m => new { m.DateDue }).Select(m => new { NumberOfProjects = m.Count(), DueOn = m.Key.DateDue });
    return View(models);
}

Helper Extensions:

    public static MvcHtmlString BuildHeaders(this HtmlHelper html, Type type)
    {
        var tr = new TagBuilder("tr");
        var model = type;
        foreach (MemberInfo prop in model.GetProperties())
        {
            var th = new TagBuilder("th");
            var display = prop.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;
            if (display != null) th.InnerHtml = display.Name;
            else if (!prop.Name.Contains("Id")) th.InnerHtml = prop.Name;
            else continue;
            tr.InnerHtml += th.ToString();
        }
        return MvcHtmlString.Create(tr.ToString());
    }
    public static MvcHtmlString BuildRow(this HtmlHelper html, object model)
    {
        var tr = new TagBuilder("tr");
        var type = model.GetType();
        foreach (PropertyInfo prop in type.GetProperties())
        {
            var td = new TagBuilder("td");
            var val = prop.GetValue(model, null);
            string valString = "";
            if (val != null) valString = val.ToString();
            if (!prop.Name.Contains("Id")) td.InnerHtml = valString;
            else continue;
            tr.InnerHtml += td.ToString();
        }
        return MvcHtmlString.Create(tr.ToString());
    }

List View:

@model IEnumerable<object>
@{
    ViewBag.Title = "Index";
    Type type = Model.GetType().GetGenericArguments()[1]; //this line if I'm using an anonymous type
    Type type = Model.GetType().GetGenericArguments()[0]; //this line if I'm using a named type.  I need to make this line handle both situations without manual intervention

}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    @Html.BuildHeaders(type)

@foreach (object item in Model) {
    @Html.BuildRow(item)
}
</table>





Aucun commentaire:

Enregistrer un commentaire