How to display more than one model in a view in MVC 2

Home > Search > How-to
  by

Let's say you have two tables in SQL, table1 and table2, and you want to display data from both tables in a view, such as www.example.com/Home/Details/1.

table1  
id 1
column1 foo

 

table2  
id 1
column1 bar

 


MODEL

In your model, ensure you have a public class table1 and a public class table2.

namespace example.Models
{    
    public class table1
    {
        public int id { get; set; }
        public string column1{ get; set; }
    }

    public class table2
    {
        public int id { get; set; }
        public string column1 { get; set; }
    }

    public class example_db : DbContext
    {
        public DbSet<table1> foo { get; set; }
        public DbSet<table2> bar { get; set; }
    }
}

 


You should have two contollers, table1Controller and table2Controller. Each controller should have a Details section.

TABLE1CONTROLLER

namespace example.com.Controllers
{
    public class Table1Controller : Controller
    {
        private example_db db = new example_db();

        public ActionResult Details(int? id)
        {
            Table1 table1 = db.Table1.Find(id);
            return View(table1);
        }
    }
}

 

TABLE2CONTROLLER

namespace example.com.Controllers
{
    public class Table2Controller : Controller
    {
        private example_db db = new example_db();

        public ActionResult Details(int? id)
        {
            Table2 table2 = db.Table2.Find(id);
            return View(table1);
        }
    }
}

 


You should have two views, /View/Table1/Details and /View/Table2/Details. Each view should start with a unique model. Also, each view should display the data from it's table.

TABLE1 VIEW

@model www.example.com.Models.Table1

@Html.DisplayFor(model => model.column1)

Navigating to www.example.com/Table1/Details/1 will display foo.

 

TABLE2 VIEW

@model www.example.com.Models.Table2

@Html.DisplayFor(model => model.column1)

Navigating to www.example.com/Table1/Details/1 will display bar.

 


PUTTING IT ALL TOGETHER

Create a new Razor view. Let's name it Combined.

@{
    Html.RenderPartial("table1", www.example.com.Models.table1);
}

@{
    Html.RenderPartial("table2", www.example.com.Models.table2);
}

 

Add the following to the CONTROLLER.

public ActionResult Combined(int? id)
{
    Table1 table1 = db.Table1.Find(id);
    return View(table1);
}

 

Now, when navigating to www.example.com/Table1/Combined/1, both foo and bar are displayed.

 

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments