Download Sample Source Code-Using Multiple Models In Single View ASP.NET_MVC_5.zip


Introduction

 

Most of the real work application requires to show data from multiple/different Models / Tables / Databases. Showing multiple models in a view is common requirement, that's where I started different ways to achieve this.

Best approaches of passing / using multiple models (objects) in one view in ASP.NET MVC 4 / MVC 5 are as follows:

  1. Using Combined Model (Model with multiple objects)

  2. Using Partial Views

  3. Using Ajax

  4. Data Carrier in MVC

    • ViewBag

    • ViewData

    • TempData

Background

Please download sample code so that you can follow code along with documentation.

Once you build and run code you will see -

UsingMultipleModules_ASP_NET_MVC_1

Here I have provided menu option for each approach. What you can do is as you proceed each approach run application click on corresponding menu option and review code.

Using the code

  1. Create ASP.NET MVC 4 Project

Open Visual studio and select ASP.NET MVC 4 Template

UsingMultipleModules_ASP_NET_MVC_2

  1. Select Project Template

    I am are using Intranet template with Razor view engine.

UsingMultipleModules_ASP_NET_MVC_3

  1. Setting Up Test Data  and Models

Add Author.cs and Book.cs file in Models folder

Author.cs  -
public class Author

{

public Author(int authorID, string authorString, int authorRating, List bookPublished)

{

this.AuthorID = authorID;

this.AuthorTitle = authorString;

this.AuthorRating = authorRating;

this.BookPublished = bookPublished;

}

public int AuthorID;

public string AuthorTitle;

public int AuthorRating;

public List BookPublished { get; set; }

}

Book.cs -

public class Book

{ 

public Book(int bookID, string bookString, int bookRating)

{

this.BookID = bookID;

this.BookTitle = bookString;

this.BookRating = bookRating;

}

public int BookID;

public string BookTitle;

public int BookRating;

}

 

  1. Add ‘DataSource.cs’ file to populate dummy data

 

public class DataSource

{

public List GetBooks()

{

return new List {

new Book (1, "Life of Star", 5),

new Book (2, "Game of Star", 2),

new Book (3, "TBD", 4) ,

new Book (4, "Life of Moon", 5),

new Book (5, "Game of Moon", 2),

new Book (6, "TBD", 4) 

};

}

public List GetAuthors()

{

return new List {

new Author (1, "John", 5, new List {1, 2 }) ,

new Author (2, "Tom", 5, new List {3,6}) ,

new Author (3, "Tim", 5, new List {4,5})

};

}

public List GetTop2Books()

{

return new List {

new Book (1, "Life of Star", 5),

new Book (5, "Life of Moon", 2),

};

}

}

 

  1. Make Home/Index view as follows

 

@{

ViewBag.Title = "Home Page";

}<h1>Use menu options to see how it works !!!</h1>

 

  1. Add styles for each model in Content/Site.css

 

/*Models css*/

.FirstTable {

background-color:#8ECD35;

width:200px;
}

.SecondTable {

background-color:#F4901E;

width:200px;

}

.ThirdTable {

background-color:#FFBB00;

width:200px;

}

.FirstTableDiv, .SecondTableDiv, .ThirdTableDiv, .Separator {

float:left;

}

.Separator {

 width:10px;

}

 

Using Combined Model (Model with multiple objects)

 

  1. Create Combined Model ()

public class MyViewModel

{

public List Books { get; set; }

public List Authors { get; set; }

public List TopBooks { get; set; }

}
  1. Add ‘GetAllModels’ Action in Home Controller

In code below you will notice that return type is ‘MyViewModel’ which consist of Books, Authors and Top Books.

DataSource db = new DataSource();

public ActionResult GetAllModels() {

var viewModels = new DataSource.MyViewModel

{

Books = db.GetBooks(),

Authors = db.GetAuthors(),

TopBooks = db.GetTop2Books()

};

return View(viewModels);

}
  1. Add View - Home/GetAllModels.cshtml

@model UsingMultipleModels.Models.DataSource.MyViewModel

@{
ViewBag.Title = "Using Combined Model -Get All Models From One Action";
}

<h2>@ViewBag.Title</h2>
<div>
 <div class="FirstTableDiv">
 <table class="FirstTable">
 <tr>
 <th>
 Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model.Books)
 {
 <tr>
 <td>
 @item.BookTitle
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
 </div>
 <div class="Separator"> </div>
 <div class="SecondTableDiv">
 <table class="SecondTable">
 <tr>
 <th>
 Authors<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model.Authors)
 {
 <tr>
 <td>
 @item.AuthorTitle;
 </td>
 <td>
 @item.AuthorRating
 </td>
 </tr>
 }

 </table>
 </div>
 <div class="Separator"> </div>
 <div class="ThirdTableDiv">
 <table class="ThirdTable">
 <tr>
 <th>
 Top Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model.TopBooks)
 {
 <tr>
 <td>
 @item.BookTitle;
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
 </div>
</div>
  1. Will Add Link In Site Menu Options

@Html.ActionLink("Home", "Index", "Home") 
@Html.ActionLink("Using Combined Model", "GetAllModels", "Home")

Using Partial View:

Here we are only passing main object (Model) and will create separate action methods for partial view

  1. Add Action method for partial view

public ActionResult PartialViews()

{

return View(db.GetBooks());

}
  1. Add View - Home/PartialViews.cshtml

@model IEnumerable<UsingMultipleModels.Models.Book>

 @{
 ViewBag.Title = "Using PartialViews-Independent action and views ";
 }

 <h2>Using Partial Views - Get Models From Different Action </h2>

 <div>
 <div class="FirstTableDiv">
 <table class="FirstTable">
 <tr>
 <th>
 Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model)
 {
 <tr>
 <td>
 @item.BookTitle
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
 </div>
 <div class="Separator"> </div>
 @Html.Partial("_GetAuthors")
 <div class="Separator"> </div>
 @Html.Partial("_GetTop2Books")
 </div>
  1. Add ‘GetAuthors’ and ‘GetTop2Books’ Actions In Home Controller

public ActionResult GetAuthors()

{

return View(db.GetAuthors());

}

public ActionResult GetTop2Books()

{

return View(db.GetTop2Books());

}
  1. Add Views - ‘Home/_GetAuthors.cshtml’ and ‘Home/_GetTop2Books.cshtml’

_GetAuthors.cshtml

@{
var authors = new UsingMultipleModels.Models.DataSource().GetAuthors();
}
<div class="SecondTableDiv">
 <table class="SecondTable">
 <tr>
 <th>
 Authors<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in authors)
 {
 <tr>
 <td>
 @item.AuthorTitle
 </td>
 <td>
 @item.AuthorRating
 </td>
 </tr>
 }

 </table>
</div>
 

_GetTop2Books.cshtml

@{
var topBooks = new UsingMultipleModels.Models.DataSource().GetTop2Books();
}

<div class="ThirdTableDiv">
 <table class="ThirdTable">
 <tr>
 <th>
 Top Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in topBooks)
 {
 <tr>
 <td>
 @item.BookTitle;
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
</div>
  1. Will Add Link In Site Menu Options

@Html.ActionLink("Home", "Index", "Home") 
@Html.ActionLink("Using Combined Model", "GetAllModels", "Home") 
@Html.ActionLink("Using Partial Views", "PartialViews", "Home")

Using Ajax

  1. Add ‘AjaxView’ Action In Home Controller

public ActionResult AjaxView()

{

return View(db.GetBooks());

}
  1. Add View - ‘Home/AjaxView.cshtml’

@model IEnumerable<UsingMultipleModels.Models.Book>

@{
    ViewBag.Title = "Using Ajax Views-Get Models From Different Action Independent action and views";
}

<h2>Using Ajax -Get Models From Different Action  Using Ajax </h2>

<div>
    <div class="FirstTableDiv">
        <table class="FirstTable">
            <tr>
                <th>Books<hr />
                </th>
                <th>Rating<hr />
                </th>
            </tr>

            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @item.BookTitle
                    </td>
                    <td>
                        @item.BookRating
                    </td>
                </tr>
            }
        </table>
    </div>
    <div class="Separator"> </div>
    <div id="Section_Authors"></div>
    <div class="Separator"> </div>
    <div id="Section_Top2Books"></div>
   
</div>

 

  1. Add Views - ‘Home/GetAuthors.cshtml’ and ‘Home/GetTop2Books.cshtml’

GetAuthors.cshtml

 
 @model IEnumerable<UsingMultipleModels.Models.Author>
 @{
 Layout = string.Empty;
 }

 <div class="SecondTableDiv">
 <table class="SecondTable">
 <tr>
 <th>
 Authors<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model)
 {
 <tr>
 <td>
 @item.AuthorTitle
 </td>
 <td>
 @item.AuthorRating
 </td>
 </tr>
 }

 </table>
 </div>
 

GetTop2Books.cshtml

@model IEnumerable<usingmultiplemodels.models.book>
@{
 Layout = string.Empty;
}

<div class="ThirdTableDiv">
 <table class="ThirdTable">
 <tr>
 <th>
 Top Books<hr />
 </th>
 <th>
 Rating<hr />
 </th>
 </tr>

 @foreach (var item in Model)
 {
 <tr>
 <td>
 @item.BookTitle;
 </td>
 <td>
 @item.BookRating
 </td>
 </tr>
 }

 </table>
</div>
  1. Will Add Link In Site Menu Options

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Using Combined Model", "GetAllModels", "Home")

@Html.ActionLink("Using Partial Views", "PartialViews", "Home")

@Html.ActionLink("Using Ajax-Multiple", "AjaxView", "Home")

Using Data Carrier in MVC

Which data carrier you should be using based on its features. In this approach you will assign different Model object to data carrier (ViewBag/ViewData/TempData) and access it from view.

  1. ViewBag

    It is most popular data carrier in MVC because ViewBag is dynamic property and doesn't requires typecasting.

  2. ViewData

    It is dictionary object derived from ViewDataDictionary class, requires typecasting for complex data type and need check for null values for to avoid errors.

  3. TempData

    It is dictionary object derived from TempDataDictionary class, data is stored in short lives session.


Download Sample Source Code-Using_Multiple_Models.zip


Please like this article on social site if this worked for you… Coding is fun !!! Isn't it...