ViewBag-Fiddle

CSharp · Mvc

Model

using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;

namespace DemoApp
{
	public class Person
	{
		public Person(int id, string name)
		{
		    Id = id;
			Name = name;
		}
		
		public int Id { get; set; }
		public string Name { get; set; }
	}
}

View

@{
	Layout = null;
}

<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->

<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>Bootstrap 101 Template</title>

		<!-- CSS Includes -->
		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
	</head>
	
	<body>
		<h3>Person Table</h3>
		<table>
			@foreach(var item in ViewBag.List)
			{
    			<tr>
        			<td>@item.Id <td>
        			<td>@item.Name </td>
    			</tr>
			}
		</table>
	</body>
</html>

Controller

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace DemoApp
{
	public class HomeController : Controller
	{
		
		[HttpGet]
		public ActionResult Index()
		{
		    ViewBag.List = GetList();
			return View();
		}
		
		private List<Person> GetList()
		{
		    return new List<Person>()
			{
			    new Person(1, "Cyrus"),
				new Person(2, "Roxana")
			};
		}
	}
}
;