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.

Syntax

public ViewDataDictionary ViewData { get; set; }

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()
        {
            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>

<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewData["Name"]       <br />
        @ViewData["SurName"]    <br />
        @ViewData["Age"]        <br />
        @ViewData["Address"]

    </div>
</body>
</html>

Output

Any name
Any Surname
35
1234, this and that block

Share

You may also like...