How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
Snesh Prajapati, 8 Dec 2014
http://www.codeproject.com/Articles/717941/How-to-Choose-the-Best-Way-to-Pass-Multiple-Models
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:
- ViewModel
- Partial View
- ViewBag
- ViewData
- TempData
- 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 soViewBag 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 asViewBag.Message, etc.
Advantages
- Using
ViewBag, we can send data from controller to view with minimal efforts. - Syntax of
ViewBagis better thanViewData. No need to use key. ViewBagdoesn’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
ViewBagpersists only during current request. Its value cannot persist between requests so if redirection occurs, then its value becomesnull. - 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
ViewDatabut 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 ViewDatafor 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
ViewDatapersists only during current request. Its value cannot persist between requests so if redirection occurs, then its value becomesnull. - 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
ViewBagwhich 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
nullvalues 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
- [1] http://stackoverflow.com/questions/664205/viewmodel-best-practices
- [2] http://www.codeproject.com/Articles/193537/C-4-Tuples
- [3] http://stackoverflow.com/questions/1500402/when-to-use-tempdata-vs-session-in-asp-net-mvc
- [4] http://www.webcodeexpert.com/2013/12/what-is-use-of-viewbag-viewdata-and_3.html
How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC的更多相关文章
- WPF – pass multiple parameters to a Command
public class SendCommand : ICommand { public void Execute(object parameter) { var labels = ((object[ ...
- How to pass multiple parameters in PowerShell invoke-restmethod
Link: http://www.tagwith.com/question_322855_how-to-pass-parameters-in-powershell-invoke-restmethod- ...
- MVC到底使用哪种方式传递Model,在ViewData、ViewBag、PartialView、TempData、ViewModel、Tuple之间取舍
在"MVC控制器传递多个Model到视图,使用ViewData, ViewBag, 部分视图, TempData, ViewModel, Tuple"中,体验了使用不同的方式传递多 ...
- Incorporating ASP.NET MVC and SQL Server Reporting Services, Part 1
Your ASP.NET MVC application needs reports. What do you do? In this article, I will demonstrate how ...
- WebForm vs MVC
What is ASP.NET? ASP.NET is a Microsoft’s Web application framework built on Common language runtime ...
- Fedora 22中的DNF软件包管理工具
Introduction DNF is the The Fedora Project package manager that is able to query for information abo ...
- (转) [it-ebooks]电子书列表
[it-ebooks]电子书列表 [2014]: Learning Objective-C by Developing iPhone Games || Leverage Xcode and Obj ...
- DotNet 资源大全中文版(Awesome最新版)
Awesome系列的.Net资源整理.awesome-dotnet是由quozd发起和维护.内容包括:编译器.压缩.应用框架.应用模板.加密.数据库.反编译.IDE.日志.风格指南等. 算法与数据结构 ...
- 【ASP.NET Identity系列教程(二)】运用ASP.NET Identity
注:本文是[ASP.NET Identity系列教程]的第二篇.本系列教程详细.完整.深入地介绍了微软的ASP.NET Identity技术,描述了如何运用ASP.NET Identity实现应用程序 ...
随机推荐
- Indy发送邮件被kbas退掉
用indy开发了发送邮件程序,通过126,sina等发送邮件可以发送出去,而通过tom,163则被退回,显示被 kbas系统退回.后来通过观察Foxmail的通讯过程,区别在foxmail发送EHLO ...
- tomcat 1字节的UTF-8序列的字节1无效
微信支付时, 命名返回支付成功, 但是成功后却返回如下的错误, 在测试环境都是没有任何问题, 到客户现场后, 可能客户现场使用的4G网络, 用微信支付时一直报这样的错误 错误现象: com.sun.o ...
- 16c550芯片编写的优化
参考了 <Altera FPGA/CPLD 设计>高级篇, 关于状态机的推荐写法实现的功能是一样的但是编译使用的逻辑门如下图: 下图是我自己编的状态机需要的逻辑: 下图是使用推荐的有限状态 ...
- python使用pika链接rabbitmq Connection reset by peer 解决办法
记录一下, 最近在用机器学习打算做一个Rest API, 数据存入mongo,任务采用消息队列,rabbitmq 由于引擎采用python编写,所以WEB也直接打算用python编写了,比较省事. W ...
- Visual C++中error spawning cl.exe解决方法
点击“Tools”,选择“选项”,选择“选项”中的“目录” 目录的目录下有四个选项 需要对它们设置正确的路径 我是按照默认路径安装的 可执行文件: C:\Program Files\Microsoft ...
- js中,清空对象(删除对象的属性)
在项目中,有些对象用完后需要重置,下面简单介绍下JS中清除对象的方法.方法如下: 方法一:字面量定义对象 第一步,定义一个空对象并打印出来,代码和效果: 代码: var student = {};co ...
- STM32使用无源蜂鸣器演奏歌曲
上一次使用了有源蜂鸣器,只能发出固定的”滴滴“声,当然不能满足于此呀.使用无源蜂鸣器,只要输出不同频率的PWM波,即可发出不同的音符. 不同的音符组合起来就是一个曲子了. 改变PWM的音调,可以输出D ...
- zookpeer的安装与配置
zookpeer集群搭建: 集群搭建过程简介: 这里准3台服务器做zk(zookpeer下面简称zk)集群搭建: zk集群由一个leader和两个follower组成,对外端口默认为2181端口,关于 ...
- Class.forName和ClassLoader.loadClass区别(转)
Java中class是如何加载到JVM中的:1.class加载到JVM中有三个步骤 装载:(loading)找到class对应的字节码文件. 连接:(linking)将对应的字节码文件读入 ...
- eth0 no such device(reload)
转载自:http://blog.chinaunix.net/uid-25554408-id-292638.html 今天我在vmware里安装了虚拟机,安装虚拟机就想安装vmware tools(这个 ...