How do I dynamically create an html table given only a table name in entity framework?

My code is more like creating an engine that when passed a table name variable, will construct the table dynamically. This is the code I’m already working on. In my controller,

    public ActionResult ViewTable(string tablename)
    {
        ScsContext context = new ScsContext();
        List<string> columnNames = new List<string>();

        var html = "<table><thead><tr>";

        switch(tablename)
        {
            case "table1":

                columnNames = typeof(table1).GetProperties().Select(a => a.Name).ToList();

                foreach(var c in columnNames)
                {
                    html += "<td>" + c.ToString() + "</td>";
                }

                html += "</tr></thead><tbody>";

                var rows = from c in context.table1.ToList()
                           select c;
                foreach(var c in rows)
                {
                    foreach(var p in c.GetType().GetProperties())
                    {
                        foreach(var s in columnNames)
                        {
                            if(p.Name == s.ToString())
                            {
                                // How do I get the value here?
                            }
                        }
                    }

                }

                break;

            // more case statements here based on table names
            default:
                break;
        }


        // return empty for now
        return new EmptyResult();

    }

I was able to loop the names of my columns in my entities, as above, and now constructing my html table based on those values.. but when I need to get the value now, I’m stucked. How do I get the value from my properties above to construct my html table based on table name variable?

And since I have more hundred tables the user want rendered, is there a simpler and more efficient way to do this?

Thanks very much,


Source: html

Leave a Reply