Home/MVC/How to use multiple model in view

How to use multiple model in view

If we have two model classes like Customer details and Employee detail. ASP.NET MVC allows you to pass only One model to a view. The view can be bound with one and only one model. From the above statement, we understood that either pass customer or employee details to the view. Then What if a view requires to display both models?. Let us we discuss the situation as follows:

How to overcome?

In MVC we cannot pass more than one models from a controller to the single view. To overcome this we can use ExpandoObject class.

What is ExpandoObject ?

The .NET 4.0 framework actually includes an ExpandoObject class which provides a dynamic object that allows us to add properties and methods on the fly.

  • ExpandoObject is a sealed type so we can’t use it as a base class
  • It doesn’t serialize to XML or DataContractSerializer/DataContractJsonSerializer

From msdn, Represents an object whose members can be dynamically added and removed at run time.

When to use ?

In some time we need to display more than one type of model data in to the single view. For example i am having two models namely CustomerDetails and EmployeeDetails and if i need to display both information in single view then we can use the ExpandoObject.

Example :

Model :

Creating simple model namelu CustomerDetail.cs and EmployeeDetail.cs as shown below.

CustomerDetail.cs

EmployeeDetail.cs

Controller :

View :

OUTPUT

MultipleModel

READ  ASP.NET Core Real Power: Features And Benefits

2 Comments

  1. casino malaysia February 24, 2016 at 6:44 pm

    Great article, exactly what I wanted to find.

  2. here March 3, 2016 at 3:19 pm

    Everything is very open with a really clear explanation of the challenges.

    It was definitely informative. Your website is useful.

    Thank you for sharing!

Leave A Comment