Question

I am trying to create a generic grid using PartialView. Where I will push any model and it will output some html and js so that I can reuse. But for that I need dynamic type of IEnumerable and now I need to get all the properties of the passed model from ViewData.Model since that is where I am setting the model. But I cannot find a concrete solution.
Can someone please point me to the right direction? That would be a great help.

Was it helpful?

Solution

I dont see the need for a PartialView I would instead create a HTML helper for this. THen your html helper just accepts a simple object as the model. In the helper you construct your table (using strings) and then enumerate all the properties of your object model.

This can be easily done by creating a html helper as such.

public static class HtmlHelpers
{
    public static IHtmlString ModelTableForm(this HtmlHelper html, object model)
    {
        StringBuilder modelTable = new StringBuilder();
        modelTable.Append("<table>");
        modelTable.AppendFormat("<caption>{0}</caption>", model.GetType().Name);
        modelTable.Append("<tbody>");

        foreach (var property in model.GetType().GetProperties())
            modelTable.Append(addModelRow(property.Name, property.GetValue(model, null)));
        modelTable.Append("</tbody>");
        modelTable.Append("</table>");
        return html.Raw(modelTable.ToString());
    }

    static string addModelRow(string name, object value)
    {
        StringBuilder row = new StringBuilder();
        row.Append("<tr>");
        row.AppendFormat("<td>{0}</td>", name);
        row.AppendFormat("<td>{0}</td>", value);
        row.Append("</tr>");
        return row.ToString();
    }
}

As you can see this helper simply constructs the table using strings and enumerates through all the properties creating a row for each property.

Next is to access your HTML Helper. Now this all depends on where you created the class but can be easily added to any View by using the statement

using <my full html helper namespace;

Finally to call the Helper you just need to simply call the html helper from the @Html object as.

@Html.ModelTableForm(Model)

This will generate a table (all-be-it needs more style work). As enter image description here

My suggestion would be to add some style, and maybe property type checks modifying how the helper displays different property types. (IE if the property inherits IEnumerable to enumerate all the entries and properties into a subtable by using recursion).

Anyway. Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top