Writing code in Views with ViewData

We can also write code in form of dictionary to display required output in views.ViewData Property Gets or sets a dictionary that contains data to pass between the controller and the view.


public ViewDataDictionary ViewData { get; set; }

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()
            ViewData["Name"] = "Any name";
            ViewData["SurName"] = "Any Surname";
            ViewData["Age"] = 35;
            ViewData["Address"] = "1234, this and that block";
            return View();


Index.cshtml (View)

    Layout = null;

<!DOCTYPE html>

        @ViewData["Name"]       <br />
        @ViewData["SurName"]    <br />
        @ViewData["Age"]        <br />



Any name
Any Surname
1234, this and that block


You may also like...