SlideShare a Scribd company logo
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 1/10
Introduction
In MVC we cannot use multiple model tag on a view. But Many times we need to pass multiple models from controller to view or we want to show data from multiple model on a view. For example we
want to show a Blog and List of Comments of this Blog on a Single View or suppose if we want to show a Category and List Of Products related to this category on a View. So in such situations we need
to pass multiple models to a Single View . We have many solutions of this problem. So in this article we will see different approaches to Bind Multiple Models on a View.
Problem Statement
We have two models named Blog and Comment and we want to create a view where we will show Blog Title and Blog Description and List of Comments related to the Blog.
Problem while binding two Models
If we will try to Bind Blog and Comment Model on a View as below then at run time we will get an exception that we can not Bind Multiple Models on a View.
And the exception 
So In MVC we need some approach through which we can achieve this and luckily i am giving 10 approaches to achieve the same.  I am not an expert, I'm sure I'll make mistakes or go against best
practices several times . I will not discuss the pros and cons of different approaches. My intent is to show different approaches through which we can solve this problem.
Different ways to achieve
we will see below 10 ways to bind multiple models on a single view
1. View Model
2. View Bag
3. View Data
4. Temp Data
5. Session
6. Dynamic
7. Tuples
8. Render Action
9. JSON
10. Navigation Properties
We will see all these approaches with the help of an example (Solution of above problem statement ). So in our problem statement we want to display a Blog and List of Comments on a view. 
Below are the main players of this article
1. Blog Model 
2. Comment Model 
3. GetBlog() : In this method where i will create dummy data for Blog.
4. GetComments() : In this method where i will create dummy data for comments.
5. A Controller (I will name it BlogCommentCotroller) 
6. View 
I created a project named MultipleModels and now i will create all the required elements before starting different approaches.
1. Blog Model :- Create a Model named BlogModel . Right click on Models Folder and add a class named BlogModel  . I created below BlogModel class in Models folder. 
public class BlogModel
{
public int BlogID { get; set; }
public string BlogTitle { get; set; }
public string BlogDescription { get; set; }
Hide   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 2/10
public DateTime CreatedDate { get; set; }
}
2. Comment Model :- Right click on Models folder and add another class named CommentModel as below 
public class CommentModel
{
public int CommentID { get; set; }
public string Comment { get; set; }
public string CommentedBy { get; set; }
public int BlogID { get; set; }
}
1. View Model
ViewModel is a class which contains the properties which are represented in view or represents the data that you want to display on your view/page.
Suppose if we want to create a View where we want to display a Blog and List of Comments then we will create our View Model (BlogCommentViewModel.cs) .Create a folder named ViewModel in your
project and right click on that folder and create a class file named "BlogCommentViewModel.cs" 
public class BlogCommentViewModel
{
public BlogModel Blog { get; set; }
public List<CommentModel> Comments { get; set; }
}
In above ViewModel (BlogCommentViewModel) we created a property named Blog of BlogModel Type becuase we want to display a single Blog Detail on our View/Page and a second property
named Comments of List of CommentModel type becuse we want to display the list of comments associated to the Blog.
Note : We can place the viewmodel (BlogCommentViewModel) in any folder in our project but i created a folder named ViewModel where i will place all the viewmodels created for this project.
Its time to create a controller named BlogController and create a action method inside named GetBlogComment as below  
public class BlogController : Controller
{
public ActionResult GetBlogComment()
{
return View();
}
}
Now first create a object of view Model and then set Blog and Comments properties as below. I created two functions for Blog (GetBlogModel()) and Comment (GetCommentModel())dummy data.
public class BlogController : Controller
{
public ActionResult GetBlogComment()
{
BlogCommentViewModel BCVM = new BlogCommentViewModel();
BCVM.Blog = GetBlogModel();
BCVM.Comments = GetCommentModel();
return View(BCVM);
}
public BlogModel GetBlogModel()
{
BlogModel bModel = new BlogModel() { BlogID = 1,
BlogTitle = "MVC Blog",
BlogDescription = "This is MVC Blog",
CreatedDate = DateTime.Now };
return bModel;
}
public List GetCommentModel()
{
List cModel = new List();
cModel.Add(new CommentModel() { BlogID = 1, CommentID = 1, Comment = "Good One", CommentedBy = "Vijay" });
cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Nice", CommentedBy = "Nishant" });
cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Perfect", CommentedBy = "Saurabh" });
return cModel;
}
}
Note : Don't forget to add Models and ViewModels namespaces.
Now right click on GetBlogComment() action method and select Add View and while creating view select "Create a Strongly-Typed view" and select your view model named 'BlogCommentViewModel'
and select "empty"" in scaffold Template as below
Hide   Copy Code
Hide   Copy Code
Hide   Copy Code
Hide   Shrink   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 3/10
Now change your created view (GetBlogComment.cshtml)as below
I added some table css also in Style.css
table, td, th {
border: 1px solid #ddd;
text-align: left;
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 15px;
}
Now run the application and type /Blog/GetBlogComment(ControllerName/ActionName) in browser and we will get output as below
Hide   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 4/10
2. View Bag
We use view Bag to pass data from controller to view.ViewBag use the property that takes advantage of the new dynamic features in C# 4.0.There is no typecasting needed in case of ViewBag. So we
can take help of ViewBag to pass multiple data from controller to View. ViewBag is a property of ControllerBase class.View Bag scope is only during the current request.
To pass multiple model we will create two view bag in our action method as below.
public ActionResult GetBlogComment()
{
ViewBag.Blog = GetBlogModel();
ViewBag.Comments = GetCommentModel();
return View();
}
Now change your view (GetBlogComment.cshtml) according to view Bag as below
Run the application and we will get the required output.
3. View Data
ViewData is used to pass data from controller to view.View Data scoper is only during the current request.View Data needs typecasting for getting data.ViewData is a property of ControllerBase
class.ViewData is a derivative of the ViewDataDictionary class, so we can access with “key/value” 
To use the ViewData for multiple models change your action method as below 
public ActionResult GetBlogComment()
{
ViewData["Blog"] = GetBlogModel();
ViewData["Comments"] = GetCommentModel();
return View();
}
Now change your view (GetBlogComment.cshtml) according to view Data as below
Hide   Copy Code
Hide   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 5/10
Run the application and we will get the same result as in approach 1.
4. Temp Data
TempData is also a dictionary derivative from TempDataDictionary class. TempData stored in short lives session. We can pass multiple models through TempData also. 
Change your action method as below 
 
public ActionResult GetBlogComment()
{
TempData["Blog"] = GetBlogModel();
TempData["Comments"] = GetCommentModel();
return View();
}
Now change your view (GetBlogComment.cshtml) according to Temp Data as below 
Now run the application  and we will get the required result.
5. Session
Session is used to pass data across controllers in MVC Application.Session data never expires (by default session expiration time is 20 minutes but it can be increased).Session is valid for all requests, not
for a single redirect. 
For Session, Change your action Method as below 
 
public ActionResult GetBlogComment()
{
Session["Blog"] = GetBlogModel();
Session["Comments"] = GetCommentModel();
Hide   Copy Code
Hide   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 6/10
return View();
}
Now change your view (GetBlogComment.cshtml) according to Session as below 
Run the application and we will get the expected result.
6. Dynamic (ExpandoObject)
The ExpandoObject class enables us to add and delete members at run time.So If we want to build up an object to work with on the fly at runtime then we can use Expando Object.
I am not going in detail about ExpandoObject. let's see how can we use Expando with Multiple Models. 
Change the action method as below 
 
public ActionResult GetBlogComment()
{
dynamic BCVM = new ExpandoObject();
BCVM.Blog = GetBlogModel();
BCVM.Comments = GetCommentModel();
return View(BCVM);
}
Note :To use ExpandoObject Add System.Dynamic Namespace. 
Change your view as below 
Run the application and we will get the expected result.
7. Tuples
Hide   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 7/10
Tuple is an ordered sequence, immutable, fixed-size and of heterogeneous objects. each object in tuple is being of a specific type.
Tuples are not new in programming. They are already used in F#, Python and databases. They are new to C#. The tuples were introduced in C# 4.0 with dynamic programming.
we can use Tuples also to pass multiple models to view as below 
 
public ActionResult GetBlogComment()
{
var BCVM = new Tuple<BlogModel, List<CommentModel>>(GetBlogModel(), GetCommentModel());
return View(BCVM);
}
And now change your view as below
Run the application to see the result.
8. Render Action
Render actions are special controller methods defined only to be called from view. We create Render Action Method same as we create regular Action Method.
A Render action is a public method on the controller class. Render Action is called from view not from URL so we should decorate RenderAction with the [ChildActionOnly] attribute.
I am creating two Action Methods from where i will return partial view Results and will render those results on view using RenderAction Methods.
 
public ActionResult GetBlogComment()
{
return View();
}
public PartialViewResult RenderBlog()
{
return PartialView(GetBlogModel());
}
public PartialViewResult RenderComments()
{
return PartialView(GetCommentModel());
}
Right click on RenderBlog() and add a view as below (Make sure we need to create a partial view so check that option) 
Hide   Copy Code
Hide   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 8/10
Now change the code of your created partial(RenderBlog.cshtml) view as below
Same way right click on RenderComments and create another partial view as below
change this partial view(RenderComments.cshtml) as below
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 9/10
Its time to render these two partial view on our main view named GetBlogComment.cshtml. 
Now run the application and we will get the required result.
9. JSON
We can Bind Multiple Models with the help of Json as well. We will retun JsonResult from action Method and on View through JQuery we can pasrse the JSON data and Bind on View. Here is the code 
Change your action method so that Action Method can return the JSON 
 
public ActionResult GetBlogComment()
{
return View();
}
public JsonResult RenderBlog()
{
return Json(GetBlogModel());
}
public JsonResult RenderComments()
{
return Json(GetCommentModel());
}
Change your view as below 
Hide   Copy Code
12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject
https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 10/10
10. Navigation Properties
If we have two related models then we can bind a model into another model as a property and can pass to a View. For example we have a Blog Model and Comment Model and A blog can contains
multiple comments so we can declare a Navigation Property in Blog Model as below
 
public class BlogModel
{
public int BlogID { get; set; }
public string BlogTitle { get; set; }
public string BlogDescription { get; set; }
public DateTime CreatedDate { get; set; }
public List<CommentModel> Comments { get; set; } //Navigation Property
}
Now change your GetBlogModel() function and GetBlogComment() Action as below 
 
public ActionResult GetBlogComment()
{
BlogModel BM = GetBlogModel();
return View(BM);
}
public BlogModel GetBlogModel()
{
BlogModel bModel = new BlogModel()
{
BlogID = 1,
BlogTitle = "MVC Blog",
BlogDescription = "This is MVC Blog",
Hide   Copy Code
Hide   Shrink   Copy Code
Ad

More Related Content

What's hot (20)

POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Implementing auto complete using JQuery
Implementing auto complete using JQueryImplementing auto complete using JQuery
Implementing auto complete using JQuery
Bhushan Mulmule
 
Android Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUKAndroid Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUK
Fabio Collini
 
Creating Openbravo Workspace Widgets
Creating Openbravo Workspace WidgetsCreating Openbravo Workspace Widgets
Creating Openbravo Workspace Widgets
Rob Goris
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry university
lhkslkdh89009
 
Create a meteor chat app in 30 minutes
Create a meteor chat app in 30 minutesCreate a meteor chat app in 30 minutes
Create a meteor chat app in 30 minutes
Designveloper
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
jojule
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
Edureka!
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
Joonas Lehtinen
 
Fewd week8 slides
Fewd week8 slidesFewd week8 slides
Fewd week8 slides
William Myers
 
Mixpanel Integration in Android
Mixpanel Integration in AndroidMixpanel Integration in Android
Mixpanel Integration in Android
mobi fly
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
rohitkumar1987in
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questions
codeandyou forums
 
Fewd week7 slides
Fewd week7 slidesFewd week7 slides
Fewd week7 slides
William Myers
 
Vaadin Components
Vaadin ComponentsVaadin Components
Vaadin Components
Joonas Lehtinen
 
Secure mvc application saineshwar
Secure mvc application   saineshwarSecure mvc application   saineshwar
Secure mvc application saineshwar
Saineshwar bageri
 
iOS Contact List Application Tutorial
iOS Contact List Application TutorialiOS Contact List Application Tutorial
iOS Contact List Application Tutorial
Ishara Amarasekera
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular js
codeandyou forums
 
Working with AngularJS
Working with AngularJSWorking with AngularJS
Working with AngularJS
André Vala
 
Revit drafting procedure
Revit drafting procedureRevit drafting procedure
Revit drafting procedure
Anima M C
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Implementing auto complete using JQuery
Implementing auto complete using JQueryImplementing auto complete using JQuery
Implementing auto complete using JQuery
Bhushan Mulmule
 
Android Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUKAndroid Data Binding in action using MVVM pattern - droidconUK
Android Data Binding in action using MVVM pattern - droidconUK
Fabio Collini
 
Creating Openbravo Workspace Widgets
Creating Openbravo Workspace WidgetsCreating Openbravo Workspace Widgets
Creating Openbravo Workspace Widgets
Rob Goris
 
Cis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry universityCis407 a ilab 6 web application development devry university
Cis407 a ilab 6 web application development devry university
lhkslkdh89009
 
Create a meteor chat app in 30 minutes
Create a meteor chat app in 30 minutesCreate a meteor chat app in 30 minutes
Create a meteor chat app in 30 minutes
Designveloper
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
jojule
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
Edureka!
 
Vaadin Components @ Angular U
Vaadin Components @ Angular UVaadin Components @ Angular U
Vaadin Components @ Angular U
Joonas Lehtinen
 
Mixpanel Integration in Android
Mixpanel Integration in AndroidMixpanel Integration in Android
Mixpanel Integration in Android
mobi fly
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questions
codeandyou forums
 
Secure mvc application saineshwar
Secure mvc application   saineshwarSecure mvc application   saineshwar
Secure mvc application saineshwar
Saineshwar bageri
 
iOS Contact List Application Tutorial
iOS Contact List Application TutorialiOS Contact List Application Tutorial
iOS Contact List Application Tutorial
Ishara Amarasekera
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular js
codeandyou forums
 
Working with AngularJS
Working with AngularJSWorking with AngularJS
Working with AngularJS
André Vala
 
Revit drafting procedure
Revit drafting procedureRevit drafting procedure
Revit drafting procedure
Anima M C
 

Similar to 10 ways to bind multiple models on a view in mvc code project (20)

LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
MVC Training Part 2
MVC Training Part 2MVC Training Part 2
MVC Training Part 2
Lee Englestone
 
MVC Training Part 1
MVC Training Part 1MVC Training Part 1
MVC Training Part 1
Lee Englestone
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
Alfa Gama Omega
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
Bhavin Shah
 
ASP.NET Identity
ASP.NET IdentityASP.NET Identity
ASP.NET Identity
Suzanne Simmons
 
Asp 2-createaspnetmvc
Asp 2-createaspnetmvcAsp 2-createaspnetmvc
Asp 2-createaspnetmvc
Fajar Baskoro
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web
MahmoudOHassouna
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
M Ahsan Khan
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Sony Suci
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)
Ruud van Falier
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
Stefano Paluello
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
Model View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In AspnetModel View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In Aspnet
rainynovember12
 
MVC 4
MVC 4MVC 4
MVC 4
Vasilios Kuznos
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
alifha12
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
Alfa Gama Omega
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
Bhavin Shah
 
Asp 2-createaspnetmvc
Asp 2-createaspnetmvcAsp 2-createaspnetmvc
Asp 2-createaspnetmvc
Fajar Baskoro
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web
MahmoudOHassouna
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
M Ahsan Khan
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Sony Suci
 
Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)Sitecore MVC (London User Group, April 29th 2014)
Sitecore MVC (London User Group, April 29th 2014)
Ruud van Falier
 
Simple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnanSimple mvc4 prepared by gigin krishnan
Simple mvc4 prepared by gigin krishnan
Gigin Krishnan
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
Alicia Buske
 
Model View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In AspnetModel View Presenter (MVP) In Aspnet
Model View Presenter (MVP) In Aspnet
rainynovember12
 
Mvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senjaMvc4 crud operations.-kemuning senja
Mvc4 crud operations.-kemuning senja
alifha12
 
Ad

Recently uploaded (20)

How to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptxHow to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptx
engaash9
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution ControlDust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Janapriya Roy
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
comparison of motors.pptx 1. Motor Terminology.ppt
comparison of motors.pptx 1. Motor Terminology.pptcomparison of motors.pptx 1. Motor Terminology.ppt
comparison of motors.pptx 1. Motor Terminology.ppt
yadavmrr7
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis""Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
Infopitaara
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Basic Principles for Electronics Students
Basic Principles for Electronics StudentsBasic Principles for Electronics Students
Basic Principles for Electronics Students
cbdbizdev04
 
BCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdfBCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdf
VENKATESHBHAT25
 
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
Kamal Acharya
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
How to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptxHow to Make Material Space Qu___ (1).pptx
How to Make Material Space Qu___ (1).pptx
engaash9
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution ControlDust Suppressants: A Sustainable Approach to Dust Pollution Control
Dust Suppressants: A Sustainable Approach to Dust Pollution Control
Janapriya Roy
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
comparison of motors.pptx 1. Motor Terminology.ppt
comparison of motors.pptx 1. Motor Terminology.pptcomparison of motors.pptx 1. Motor Terminology.ppt
comparison of motors.pptx 1. Motor Terminology.ppt
yadavmrr7
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis""Heaters in Power Plants: Types, Functions, and Performance Analysis"
"Heaters in Power Plants: Types, Functions, and Performance Analysis"
Infopitaara
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Basic Principles for Electronics Students
Basic Principles for Electronics StudentsBasic Principles for Electronics Students
Basic Principles for Electronics Students
cbdbizdev04
 
BCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdfBCS401 ADA Second IA Test Question Bank.pdf
BCS401 ADA Second IA Test Question Bank.pdf
VENKATESHBHAT25
 
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.
Kamal Acharya
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Ad

10 ways to bind multiple models on a view in mvc code project

  • 1. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 1/10 Introduction In MVC we cannot use multiple model tag on a view. But Many times we need to pass multiple models from controller to view or we want to show data from multiple model on a view. For example we want to show a Blog and List of Comments of this Blog on a Single View or suppose if we want to show a Category and List Of Products related to this category on a View. So in such situations we need to pass multiple models to a Single View . We have many solutions of this problem. So in this article we will see different approaches to Bind Multiple Models on a View. Problem Statement We have two models named Blog and Comment and we want to create a view where we will show Blog Title and Blog Description and List of Comments related to the Blog. Problem while binding two Models If we will try to Bind Blog and Comment Model on a View as below then at run time we will get an exception that we can not Bind Multiple Models on a View. And the exception  So In MVC we need some approach through which we can achieve this and luckily i am giving 10 approaches to achieve the same.  I am not an expert, I'm sure I'll make mistakes or go against best practices several times . I will not discuss the pros and cons of different approaches. My intent is to show different approaches through which we can solve this problem. Different ways to achieve we will see below 10 ways to bind multiple models on a single view 1. View Model 2. View Bag 3. View Data 4. Temp Data 5. Session 6. Dynamic 7. Tuples 8. Render Action 9. JSON 10. Navigation Properties We will see all these approaches with the help of an example (Solution of above problem statement ). So in our problem statement we want to display a Blog and List of Comments on a view.  Below are the main players of this article 1. Blog Model  2. Comment Model  3. GetBlog() : In this method where i will create dummy data for Blog. 4. GetComments() : In this method where i will create dummy data for comments. 5. A Controller (I will name it BlogCommentCotroller)  6. View  I created a project named MultipleModels and now i will create all the required elements before starting different approaches. 1. Blog Model :- Create a Model named BlogModel . Right click on Models Folder and add a class named BlogModel  . I created below BlogModel class in Models folder.  public class BlogModel { public int BlogID { get; set; } public string BlogTitle { get; set; } public string BlogDescription { get; set; } Hide   Copy Code
  • 2. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 2/10 public DateTime CreatedDate { get; set; } } 2. Comment Model :- Right click on Models folder and add another class named CommentModel as below  public class CommentModel { public int CommentID { get; set; } public string Comment { get; set; } public string CommentedBy { get; set; } public int BlogID { get; set; } } 1. View Model ViewModel is a class which contains the properties which are represented in view or represents the data that you want to display on your view/page. Suppose if we want to create a View where we want to display a Blog and List of Comments then we will create our View Model (BlogCommentViewModel.cs) .Create a folder named ViewModel in your project and right click on that folder and create a class file named "BlogCommentViewModel.cs"  public class BlogCommentViewModel { public BlogModel Blog { get; set; } public List<CommentModel> Comments { get; set; } } In above ViewModel (BlogCommentViewModel) we created a property named Blog of BlogModel Type becuase we want to display a single Blog Detail on our View/Page and a second property named Comments of List of CommentModel type becuse we want to display the list of comments associated to the Blog. Note : We can place the viewmodel (BlogCommentViewModel) in any folder in our project but i created a folder named ViewModel where i will place all the viewmodels created for this project. Its time to create a controller named BlogController and create a action method inside named GetBlogComment as below   public class BlogController : Controller { public ActionResult GetBlogComment() { return View(); } } Now first create a object of view Model and then set Blog and Comments properties as below. I created two functions for Blog (GetBlogModel()) and Comment (GetCommentModel())dummy data. public class BlogController : Controller { public ActionResult GetBlogComment() { BlogCommentViewModel BCVM = new BlogCommentViewModel(); BCVM.Blog = GetBlogModel(); BCVM.Comments = GetCommentModel(); return View(BCVM); } public BlogModel GetBlogModel() { BlogModel bModel = new BlogModel() { BlogID = 1, BlogTitle = "MVC Blog", BlogDescription = "This is MVC Blog", CreatedDate = DateTime.Now }; return bModel; } public List GetCommentModel() { List cModel = new List(); cModel.Add(new CommentModel() { BlogID = 1, CommentID = 1, Comment = "Good One", CommentedBy = "Vijay" }); cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Nice", CommentedBy = "Nishant" }); cModel.Add(new CommentModel() { BlogID = 1, CommentID = 2, Comment = "Perfect", CommentedBy = "Saurabh" }); return cModel; } } Note : Don't forget to add Models and ViewModels namespaces. Now right click on GetBlogComment() action method and select Add View and while creating view select "Create a Strongly-Typed view" and select your view model named 'BlogCommentViewModel' and select "empty"" in scaffold Template as below Hide   Copy Code Hide   Copy Code Hide   Copy Code Hide   Shrink   Copy Code
  • 3. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 3/10 Now change your created view (GetBlogComment.cshtml)as below I added some table css also in Style.css table, td, th { border: 1px solid #ddd; text-align: left; } table { border-collapse: collapse; width: 100%; } th, td { padding: 15px; } Now run the application and type /Blog/GetBlogComment(ControllerName/ActionName) in browser and we will get output as below Hide   Copy Code
  • 4. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 4/10 2. View Bag We use view Bag to pass data from controller to view.ViewBag use the property that takes advantage of the new dynamic features in C# 4.0.There is no typecasting needed in case of ViewBag. So we can take help of ViewBag to pass multiple data from controller to View. ViewBag is a property of ControllerBase class.View Bag scope is only during the current request. To pass multiple model we will create two view bag in our action method as below. public ActionResult GetBlogComment() { ViewBag.Blog = GetBlogModel(); ViewBag.Comments = GetCommentModel(); return View(); } Now change your view (GetBlogComment.cshtml) according to view Bag as below Run the application and we will get the required output. 3. View Data ViewData is used to pass data from controller to view.View Data scoper is only during the current request.View Data needs typecasting for getting data.ViewData is a property of ControllerBase class.ViewData is a derivative of the ViewDataDictionary class, so we can access with “key/value”  To use the ViewData for multiple models change your action method as below  public ActionResult GetBlogComment() { ViewData["Blog"] = GetBlogModel(); ViewData["Comments"] = GetCommentModel(); return View(); } Now change your view (GetBlogComment.cshtml) according to view Data as below Hide   Copy Code Hide   Copy Code
  • 5. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 5/10 Run the application and we will get the same result as in approach 1. 4. Temp Data TempData is also a dictionary derivative from TempDataDictionary class. TempData stored in short lives session. We can pass multiple models through TempData also.  Change your action method as below    public ActionResult GetBlogComment() { TempData["Blog"] = GetBlogModel(); TempData["Comments"] = GetCommentModel(); return View(); } Now change your view (GetBlogComment.cshtml) according to Temp Data as below  Now run the application  and we will get the required result. 5. Session Session is used to pass data across controllers in MVC Application.Session data never expires (by default session expiration time is 20 minutes but it can be increased).Session is valid for all requests, not for a single redirect.  For Session, Change your action Method as below    public ActionResult GetBlogComment() { Session["Blog"] = GetBlogModel(); Session["Comments"] = GetCommentModel(); Hide   Copy Code Hide   Copy Code
  • 6. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 6/10 return View(); } Now change your view (GetBlogComment.cshtml) according to Session as below  Run the application and we will get the expected result. 6. Dynamic (ExpandoObject) The ExpandoObject class enables us to add and delete members at run time.So If we want to build up an object to work with on the fly at runtime then we can use Expando Object. I am not going in detail about ExpandoObject. let's see how can we use Expando with Multiple Models.  Change the action method as below    public ActionResult GetBlogComment() { dynamic BCVM = new ExpandoObject(); BCVM.Blog = GetBlogModel(); BCVM.Comments = GetCommentModel(); return View(BCVM); } Note :To use ExpandoObject Add System.Dynamic Namespace.  Change your view as below  Run the application and we will get the expected result. 7. Tuples Hide   Copy Code
  • 7. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 7/10 Tuple is an ordered sequence, immutable, fixed-size and of heterogeneous objects. each object in tuple is being of a specific type. Tuples are not new in programming. They are already used in F#, Python and databases. They are new to C#. The tuples were introduced in C# 4.0 with dynamic programming. we can use Tuples also to pass multiple models to view as below    public ActionResult GetBlogComment() { var BCVM = new Tuple<BlogModel, List<CommentModel>>(GetBlogModel(), GetCommentModel()); return View(BCVM); } And now change your view as below Run the application to see the result. 8. Render Action Render actions are special controller methods defined only to be called from view. We create Render Action Method same as we create regular Action Method. A Render action is a public method on the controller class. Render Action is called from view not from URL so we should decorate RenderAction with the [ChildActionOnly] attribute. I am creating two Action Methods from where i will return partial view Results and will render those results on view using RenderAction Methods.   public ActionResult GetBlogComment() { return View(); } public PartialViewResult RenderBlog() { return PartialView(GetBlogModel()); } public PartialViewResult RenderComments() { return PartialView(GetCommentModel()); } Right click on RenderBlog() and add a view as below (Make sure we need to create a partial view so check that option)  Hide   Copy Code Hide   Copy Code
  • 8. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 8/10 Now change the code of your created partial(RenderBlog.cshtml) view as below Same way right click on RenderComments and create another partial view as below change this partial view(RenderComments.cshtml) as below
  • 9. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 9/10 Its time to render these two partial view on our main view named GetBlogComment.cshtml.  Now run the application and we will get the required result. 9. JSON We can Bind Multiple Models with the help of Json as well. We will retun JsonResult from action Method and on View through JQuery we can pasrse the JSON data and Bind on View. Here is the code  Change your action method so that Action Method can return the JSON    public ActionResult GetBlogComment() { return View(); } public JsonResult RenderBlog() { return Json(GetBlogModel()); } public JsonResult RenderComments() { return Json(GetCommentModel()); } Change your view as below  Hide   Copy Code
  • 10. 12/5/2017 10 ways to Bind Multiple Models on a View in MVC - CodeProject https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-View-in-MVC 10/10 10. Navigation Properties If we have two related models then we can bind a model into another model as a property and can pass to a View. For example we have a Blog Model and Comment Model and A blog can contains multiple comments so we can declare a Navigation Property in Blog Model as below   public class BlogModel { public int BlogID { get; set; } public string BlogTitle { get; set; } public string BlogDescription { get; set; } public DateTime CreatedDate { get; set; } public List<CommentModel> Comments { get; set; } //Navigation Property } Now change your GetBlogModel() function and GetBlogComment() Action as below    public ActionResult GetBlogComment() { BlogModel BM = GetBlogModel(); return View(BM); } public BlogModel GetBlogModel() { BlogModel bModel = new BlogModel() { BlogID = 1, BlogTitle = "MVC Blog", BlogDescription = "This is MVC Blog", Hide   Copy Code Hide   Shrink   Copy Code