Writing code in Views

After successfully displaying our Hello world program, lets write some code in .CS files and then retrieve it in Our View files. Following example will demonstrate 2 Files. We are using ViewBag Property which enables you to dynamically share values from the controller to the view. It is a dynamic object which means it has no pre-defined properties. You define the properties you want the ViewBag to have by simply adding them to the property. In the view, you retrieve those values by using same name for the property.

Directory Structure

│       HomeController.cs

HomeController.cs (Controller)

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

namespace ExampleApplication.Controllers
    public class HomeController : Controller
        // GET: /Home/

        public ActionResult Index()
            ViewBag.Name = "Any name";
            ViewBag.SurName = "Any Surname";
            ViewBag.Age = 35;
            return View();


Index.cshtml (View)

    Layout = null;

<!DOCTYPE html>

        @ViewBag.Name <br />
        @ViewBag.SurName <br />
        @ViewBag.Age <br />


Any name
Any Surname


You may also like...