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

├───Controllers
│       HomeController.cs
│
└───Views
    └───Home
            Index.cshtml

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>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Name <br />
        @ViewBag.SurName <br />
        @ViewBag.Age <br />
    </div>
</body>
</html>

Output

Any name
Any Surname
35

Share

You may also like...