MVC View With Multiple Models Using Tuples And Expendo Object.

DownLoad Sample Project: MvcViewWithMultipleModels 

In mvc programming model a view can be associate with multiple models and developers have to send multiple models from controller to cshtml page.There are many  common approaches like ViewBag,ViewData,ViewModel etc can be use to achieve this functionality.

But here i am not going to demonstrate all above three approches.you can use .net framework 4.0 new features to pass the multiple models from controller to view effeciently.

  1. Expendo Object
  2. Tuples

1.) Using Expendo Object:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute(“sampleMember”).

Let say you have two models named as “Department” and “Employee” and you want bind these two models with mvc view.Below are the model definitions:

Department.cs:

c1.PNG

Employee.cs

c2

Controller.cs :

c4

Method details fetch employee and department details as per below:

c5.PNG

View (Index.Html):

On the view you have to use dynamic property of .net framework 4.0 and need to be declared as @model dynamic.this is not strongly type of view.

c6

Rendered output:

c3.PNG

2.) Using Tuples:

In C#, tuples are used to store data. It’s sort of like a variable, but in order for it to be a tuple it must contain more than one value. Each instance of a tuple has a fixed number of items within it (and each item has its own distinct type, eg. a variable or an int), and once the tuple has been created, it can’t be altered in any way.

Let’s continue with previous create models and there are no changes in model class.the only change need to do in controller and view.

Now Controller looks like after code updating for tuples:

HomeController.cs

t4

View (index.html)

you have use tuples at top of the view and you have to declare as per below:

@model Tuples<List<Employee>,List<Department>

complete view looks like:

t2.PNG

Rendered Output:

t1.PNG

You can see there is no change in final rendered output.

this article describe how to pass multiple models from controller to view .I hope this will be helpful for programmers.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s