How to send list from controller to view.
Send List from Controller to View in MVC application
In this article we will learn how to pass list from controller
to View. At first we will create model class and pass list of model class object
from controller to view.
Create model class.
Our model class is very simple. It contains only two properties
called Name and Surname. Both are string type.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVC3.Models
{
public class Customer
{
public String Name { get; set; }
public String Surname { get; set;}
}
}
Create
controller class
Now, We
will create controller class to create list of object. Our Customer controller
contains Index() action which will call view and pass list of object.
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 Index()
{
List<Customer> ObjCustomer = new List<Customer>();
Customer Obj = new Customer();
Obj.Name = "Sourav ";
Obj.Surname = "Kayal";
ObjCustomer.Add(Obj);
Obj = new Customer();
Obj.Name = "Ram";
Obj.Surname = "Kumar";
ObjCustomer.Add(Obj);
return View(ObjCustomer.ToList());
}
}
}
Razor view
Finally we will create view to display list in client part.
In below we have implemented view with the help of Razor view engine.
@model IList<MVC3.Models.Customer>
@{
// Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@foreach
(var obj in
Model) {
<li>Name:- @obj.Name</li>
<li>Surname:- @obj.Surname</li> <br />
}
</div>
</body>
</html>
ASPX View
If you are interested to use ASPX view then use below code.
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<dynamic>"
%>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
<% var V = Model; %>
<% foreach (var a in V)
{ %>
<b>Name:- </b> <%= a.Name %>
<b>Surname:-</b> <%= a.Surname%> <br />
<%} %>
</div>
</body>
</html>
At last we
will set Default controller and action for this application. Here we have set
Customer as controller and Index as action.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
// URL with parameters
new {
controller = "Customer", action = "Index", id = UrlParameter.Optional
} // Parameter defaults
);
Here is sample output

Conclusion
Here we have learned how to send List from Controller to view in MVC application