Hi friends,in this article I will explain about How to pass or send List from Controller to View
At first we will create model class and pass list of model
class object from controller to view.
Our model class is very simple. It contains only two
properties called user_Id , userName and country.
User_Id is int type userName and country
both are string type.
Model:User.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public
class User
{
public int user_Id
{ get; set; }
public string
userName { get; set;
}
public string
country { get; set;
}
}
}
|
Controller:userController.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace
MvcApplication1.Controllers
{
public
class UserController
: Controller
{
//
// GET: /User/
public ActionResult
Users()
{
List<User>
ObjUser = new List<User>();
User Obj = new User();
Obj.user_Id = 1;
Obj.userName = "Kishore";
Obj.country = "India";
ObjUser.Add(Obj);
Obj = new User();
Obj.user_Id = 2;
Obj.userName = "Satya";
Obj.country = "US";
ObjUser.Add(Obj);
Obj = new User();
Obj.user_Id = 3;
Obj.userName = "Nag";
Obj.country = "UK";
ObjUser.Add(Obj);
Obj = new User();
Obj.user_Id = 4;
Obj.userName = "Raghav";
Obj.country = "UAE";
ObjUser.Add(Obj);
return View(ObjUser.ToList());
}
}
}
|
View:Users.cshtml
@model IList<MvcApplication1.Models.User>
@{
ViewBag.Title= "Users";
}
<!DOCTYPE html>
<html>
<head>
<title>Send
List from Controller to View in MVC application</title>
<style type="text/css">
tr
{
width: 250px;
}
td
{
width: 100px;
}
</style>
</head>
<body>
<h2>
Users List</h2>
<div>
@foreach
(var obj in
Model)
{
<table style="width: 250px">
<tr>
<td>
User
ID
</td>
<td>
:
</td>
<td>
@obj.user_Id
</td>
</tr>
<tr>
<td>
User
Name
</td>
<td>
:
</td>
<td>
@obj.userName
</td>
</tr>
<tr>
<td>
Country
</td>
<td>
:
</td>
<td>
@obj.country
</td>
</tr>
</table>
}
</div>
</body>
</html>
|
Global.asax:RouteMap
routes.MapRoute(
"Default", //
Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "User",
action = "Users", id = UrlParameter.Optional } //
Parameter defaults
);
|
No comments:
Post a Comment