How to display data from multiple model in single view
Display multiple model data in single view
In this article we will discuss on how to display
multiple model data in single view. Generally we use strong type view to achieve
this goal. Here we will use collection from to show data from multiple modes.
First of all we will create one
interface like below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3.Models
{
public interface ICustomer
{
}
}
Create Customer class and derive it from ICustomer interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3.Models
{
public class Customer:ICustomer
{
public Int32 CId { get; set; }
public String CustomerName { get; set;}
}
}
Create CustomerLocation class and derive it from ICustomer interface.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3.Models
{
public class CustomerLocation:ICustomer
{
public Int32 CID {get; set; }
public String Location { get; set;}
}
}
Now, we will create Customer controller which will contain
ShowCustomer() action. Within this action we will create object of both
Customer and CustomerLocation class. Then we will create ICustomer List to store both objects.
Then we are passing List data through ViewBag.
Note:- ViewBag will not work in MVC 1 and MVC 2. We have to
use at least MVC3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3.Models;
namespace MVC3.Controllers
{
public class CustomerController : Controller
{
public ActionResult ShowCustomer()
{
Customer c = new Customer();
CustomerLocation l = new CustomerLocation();
c.CId = 1;
c.CustomerName = "Sourav";
l.CID = c.CId;
l.Location = "Kolkata";
List<ICustomer> List = new List<ICustomer>();
List.Add(c);
List.Add(l);
ViewBag.Customers = List;
return View();
}
}
}
Now, we will create view to show data
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<dynamic>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
<title>ShowCustomer</title>
</head>
<body>
<div>
<% var Value= (List<MVC3.Models.ICustomer>) ViewBag.Customers; %>
<% var CInfo = Value[0] as MVC3.Models.Customer; %>
<% var CLoc = Value[1] as MVC3.Models.CustomerLocation; %>
Customer ID:- <%= CInfo.CId %> <br />
Customer Name:- <%= CInfo.CustomerName %><br />
Customer Location :- <%= CLoc.Location %>
</div>
</body>
</html>
Here is output:

Conclusion:-
In this article,we have learned how to display multiple model data in view. Hope you have understood the concept.