Search code examples
asp.net-mvc-3model-view-controllerdynamicmodeldynamic-data

How to use one view/model in MVC3 with entity data modle to handle multiple tables?


I have database mapped into a entity framework and then I have controllers, views to display those tables(entities). I am thinking to create one generic view to display data from different table.

To display one table, I have the following:

public class ATaskController : Controller
{
    private MY_DATA_SQLEntities db = new MY_DATA_SQLEntities();


    //
    // GET: /ATask/

    public ViewResult Index()
    {

        return View(db.ATask.ToList());
    }
}

In my view:

@model IEnumerable<JRAM_MVC.ATask>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.position)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
 </tr>
}

The above is only for one table and it works perfectly. But I have many tables, I don't want to create separate controller and view for each table. What I did is as follows:

In the view part, I changed to:

@model IEnumerable<JRAM_MVC.ATask>

@*foreach (var item in Model)
{
<tr>
        @{
Type t = item.GetType();
foreach (PropertyInfo k in t.GetProperties())
{
    <td>@t.GetProperty(k.Name).GetValue(item,null)</td>
}

}

this works. But troubles are:

return View(db.ATask.ToList()); // in controller

and

@model IEnumerable<JRAM_MVC.ATask>

How could I make them dynamic so that they could handle different tables just by having their names ? e.g., I will get the table name in a string variable, and the program would dynamically create "return view(db.entityfortablename.ToList()) and in view "@model IEnumerable ?

JRAM_MVC.ATask is an ObjectSet


Solution

  • You are using strongly typed views. This is not required. Use a dynamically typed view and then you should be ok with the Reflection based display of the table data. In the view

    @model dynamic

    you can pass the model information in

    ViewBag

    which allows you to add dynamic properties. One of the properties could be your IEnumerable where T is any model. You can then reference ViewBag.table (if that is the name of property that you set in the Controller

    everything else should be self evident.