Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.80/5 (74 votes)
8 Dec 2014CPOL7 min read 139.5K   108   28
How to Choose Best Way to Pass Multiple Models in ASP.NET MVC

Introduction

In this article, we will discuss how to choose the most suitable way to pass multiple models from controller to view in ASP.NET MVC. We have seen 6 such approaches, i.e., ViewModel, Patial View, Tuple, ViewData, ViewBag and TempData in the previous article "Using Multiple Models in a view in ASP.NET MVC4". We may get confused while selecting a way to be used in a particular scenario. In this article, I will share my findings on this topic.

If you have not read our previous article on Using Multiple Models in a view in ASP.NET MVC4, please have a look because the current article is based on that. The previous article has detailed discussion on how we can pass multiple models from controller to view along with a demo application in ASP.NET MVC 4. It will help you to understand the current article better.

 

Overview of Approaches

All six approaches described in the previous article have their own pros and cons. What to pick when depends upon the specific scenario in hand and obviously it is a debatable topic. Before taking any decision, we need to identify the requirement exactly then only we should choose one of those approaches by comparing the pros and cons. In this article, I would like to arrange those approaches from most to least frequently used in ASP.NET MVC applications as given below:

  1. ViewModel
  2. Partial View
  3. ViewBag 
  4. ViewData
  5. TempData
  6. Tuple

An application can use more than one approach based on the requirement at a particular point. We need to consider the best one as per the current need.
Now we will discuss the above approaches, their usages, associated pros and cons in detail.

ViewModel

ViewModel is a pattern that allow us to have multiple models as a single class. It aggregates models or contains their properties exactly as per the need of a view. ViewModel should not have methods. It should be a collection of properties needed for a view.

Typical Usages

It is the most widely used approach to pass multiple models to View in enterprise applications. It is the standard way you can use when you need to display multiple models in the view (applicable in case of partial view too).

Advantages

  • ViewModel allows us to render multiple model types in a View as a single model.
  • Great intellisense support and compile time error checking on View page.
  • ViewModel is good for security purpose also as Views have only what they exactly need. Core domain models are not exposed to user.
  • If there is any change in core domain model, you do not need to change anywhere in View code, just you need to modify corresponding ViewModel.
  • In this way, ViewModel promotes loose coupling in application.

Disadvantages

  • ViewModels add another layer between Models and Views so it increases the complexity a little bit. So for small and demo applications, we can use tuple or other ways to keep the things simple for demo.

Partial View

A Partial View is a sub-view that you can include in a parent view. In many cases, we have a situation where many Views have shared/common presentation, that common presentation is separated into a Partial View and used in other Views.

Typical Usages

This approach is also frequently used in enterprise applications along with ViewModels. It is used where you need to share the same code (Razor and HTML code) in more than one View.

Advantages

  • It promotes reusability of code (Razor and HTML code) in application.
  • It is very helpful for single page applications
  • You can use ViewModel approach to Partial View too.
  • Using Partial View, you can update a particular area of a View without refreshing the whole page using AJAX.

Disadvantages

  • If used excessively, then View becomes a just aggregation of Partial Views, so sometime readability is compromised.

ViewBag

ViewBag is a dynamic property which comes from ControllerBase class. Internally ViewBag properties are stored as name/value pairs in the dictionary. It takes advantage of the new dynamic features in C# 4.0 so ViewBag doesn’t require typecasting for data types.

Typical Usages

ASP.NET MVC 3.0 and latest versions, it is supposed to be used where a property is directly associated to View and do not fit as a model (a model is supposed to be a class encapsulating business data and behaviors). Typical examples of ViewBag are to set the title of a View using ViewBag.Title, or display some message in View as ViewBag.Message, etc.

Advantages

  • Using ViewBag, we can send data from controller to view with minimal efforts.
  • Syntax of ViewBag is better than ViewData. No need to use key.
  • ViewBag doesn’t require type casting for data types.

Disadvantages

  • It is meant for transferring data one-way only that is from controller to view.
  • The value of ViewBag persists only during current request. Its value cannot persist between requests so if redirection occurs, then its value becomes null.
  • It is certainly a bad practice to overuse ViewBag. It is not recommended in enterprise application, even though sometime it may use to transfer small data.
  • No intelligence support and compile-time error checking.
  • Technically speaking, it is slow as compared to ViewData but in real world scenarios, the difference is just negligible. (And at first place, micro optimization is bad.)

ViewData

ViewData is defined as property (type of ViewDataDictionary class) in ControllerBase class. Values stored in ViewData require typecasting to their datatype in View. The values in ViewData are accessible using a key.

Typical Usages 

In ASP.NET MVC version 1 and 2, it is used for the same purpose as ViewBag. Microsoft is supporting ViewData for newer version but as ViewBag is providing more benefits, it is better not to use ViewData with latest versions of MVC.

Advantages

  • Using ViewData, we can send data from controller to view with inbuilt feature using keys.

Disadvantages

  • It is meant for transferring data one-way only that is from controller to view.
  • The value of ViewData persists only during current request. Its value cannot persist between requests so if redirection occurs, then its value becomes null.
  • It is certainly a bad practice to overuse ViewData. It is not recommended in enterprise application, even though sometime it may use to show small data.
  • Use key syntax, so not as readable as ViewBag which uses property style syntax.
  • No intelligence support and compile-time error checking.

TempData

TempData is defined as property in ControllerBase class. It is a type of TempDataDictionary class. Values stored in TempData require typecasting to datatype in View. The values in TempData are accessible using a key. It is similar to ViewData but the difference is that it allow us to send and receive the data from one controller to another controller and from one action to another action. It is possible because it internally uses session variables.

Typical Usages

Whenever you need to hold some information till subsequent request, it is good to use TempData. It should be used when you need to hold some information like validation messages, error message or some small data which are not having any sensitive information. As it maintains the session to pass value, you should not keep sensitive data in TempData.

Advantages

  • You can pass value from one action to another action or one controller to another controller.

Disadvantages

  • It may introduce security risk as described above.
  • It requires type casting for data type and check for null values to avoid error.
  • No intellisense support in Visual Studio.

Tuple

Tuple is a new class introduced in .NET Framework 4.0. It is an ordered sequence, immutable, fixed-size collection of heterogeneous (allows us to group multiple kind of data types) objects.

Typical Usages

It may be good for small and demo applications. Tuple is a feature of C# language meant for specific scenarios (described here), but if you are using it in ASP.NET MVC, you should use Tuple only when you do not want to create ViewModel.

Advantages 

  • It provides a way to aggregate models without creating new class (ViewModel)
  • A quick remedy and need less coding efforts than ViewModel

Disadvantages

  • Tuples is fixed size maximum limit of 8 items.
  • Value is passes as item1, item2.....It is difficult to identify the arguments just by seeing the code.
  • Not a great intellisense support in Visual Studio.

Conclusion

In this article, we learned how to choose the best way to pass multiple models in ASP.NET MVC application. I hope this article will help you to understand and use those concepts in your applications in an efficient way. Your queries and comments are most welcome in this respect. Thanks.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am a Software Developer working on Microsoft technologies. My interest is exploring and sharing the awesomeness of emerging technologies.

Comments and Discussions

 
Questionthanks Pin
Member 1313547818-Apr-17 2:50
Member 1313547818-Apr-17 2:50 
AnswerRe: thanks Pin
Snesh Prajapati18-Apr-17 4:41
professionalSnesh Prajapati18-Apr-17 4:41 
QuestionAsp.net mvc 5 dynamic model Pin
Tom Joseph1-Nov-15 18:13
Tom Joseph1-Nov-15 18:13 
GeneralMy vote of 5 Pin
covijt26-May-15 7:41
covijt26-May-15 7:41 
AnswerRe: My vote of 5 Pin
Snesh Prajapati26-May-15 14:37
professionalSnesh Prajapati26-May-15 14:37 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun9-Dec-14 21:45
Humayun Kabir Mamun9-Dec-14 21:45 
AnswerRe: My vote of 5 Pin
Snesh Prajapati9-Dec-14 22:56
professionalSnesh Prajapati9-Dec-14 22:56 
GeneralMy vote of 4 Pin
Akhil Mittal25-Aug-14 0:39
professionalAkhil Mittal25-Aug-14 0:39 
AnswerRe: My vote of 4 Pin
Snesh Prajapati8-Dec-14 17:08
professionalSnesh Prajapati8-Dec-14 17:08 
GeneralGreat article. Pin
amtracc23-Jun-14 4:20
amtracc23-Jun-14 4:20 
AnswerRe: Great article. Pin
Snesh Prajapati23-Jun-14 5:49
professionalSnesh Prajapati23-Jun-14 5:49 
QuestionExcellent Summary Pin
KeithKett27-Mar-14 3:34
KeithKett27-Mar-14 3:34 
Short and to the point. You saved me a bunch of time. Thanks!
AnswerRe: Excellent Summary Pin
Snesh Prajapati27-Mar-14 3:43
professionalSnesh Prajapati27-Mar-14 3:43 
Questionnice article Pin
sankarsan parida18-Mar-14 2:55
professionalsankarsan parida18-Mar-14 2:55 
AnswerRe: nice article Pin
Snesh Prajapati18-Mar-14 2:58
professionalSnesh Prajapati18-Mar-14 2:58 
QuestionNice article Pin
Michael Breeden3-Feb-14 11:19
Michael Breeden3-Feb-14 11:19 
AnswerRe: Nice article Pin
Snesh Prajapati3-Feb-14 16:24
professionalSnesh Prajapati3-Feb-14 16:24 
Questionre: How to persist value between action methods inside a Controller Pin
RDELAN31-Jan-14 2:03
RDELAN31-Jan-14 2:03 
AnswerRe: re: How to persist value between action methods inside a Controller Pin
Snesh Prajapati31-Jan-14 2:32
professionalSnesh Prajapati31-Jan-14 2:32 
QuestionRe: re: How to persist value between action methods inside a Controller Pin
RDELAN31-Jan-14 3:08
RDELAN31-Jan-14 3:08 
AnswerRe: re: How to persist value between action methods inside a Controller Pin
Snesh Prajapati31-Jan-14 3:34
professionalSnesh Prajapati31-Jan-14 3:34 
QuestionRe: re: How to persist value between action methods inside a Controller Pin
RDELAN31-Jan-14 3:59
RDELAN31-Jan-14 3:59 
AnswerRe: re: How to persist value between action methods inside a Controller Pin
Snesh Prajapati31-Jan-14 5:19
professionalSnesh Prajapati31-Jan-14 5:19 
QuestionTuple bug Pin
David_Wimbley29-Jan-14 11:58
professionalDavid_Wimbley29-Jan-14 11:58 
AnswerRe: Tuple bug Pin
Snesh Prajapati29-Jan-14 15:38
professionalSnesh Prajapati29-Jan-14 15:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.