Strongly Typed View in ASP.NET Core MVC

Strongly Typed View in ASP.NET Core MVC Application

In this article, I will discuss how to create a Strongly Typed View in an ASP.NET Core MVC Application with Examples. Please read our previous article discussing ViewBag in an ASP.NET Core MVC Application. In ASP.NET Core MVC, Views are responsible for rendering the user interface. To display meaningful data, Views often need data from the Controller. While ASP.NET Core MVC offers several ways to pass data to Views, strongly typed Views provide a robust and maintainable way to work with data by using the power of C# type checking.

What is a Strongly Typed View in ASP.NET Core MVC?

A Strongly Typed View is a Razor view that is bound to a specific data model (class). This means the view directly knows about the shape and type of data it should expect, allowing for full IntelliSense support, compile-time type checking, and easy access to model properties.

  • The View declares the type of model it expects via the @model directive at the top of the Razor view.
  • This means you can directly access the model’s properties without casting within the view.
  • Strongly typed Views improve code clarity, maintainability, and reduce runtime errors.
Why Do We Need a Strongly Typed View in ASP.NET Core MVC?

Using strongly typed Views offers several advantages:

  • Type Safety: The compiler checks that you access properties that actually exist on the model, preventing typos and invalid property access. Therefore, errors such as typos or incorrect types are caught at compile time, not at runtime.
  • IntelliSense Support: Visual Studio (and other editors) display model properties and methods, which speeds up development and reduces errors.
  • Refactoring Safety: If you change your model (e.g., renaming a property), the compiler will alert you to update all related views.
  • Eliminates Casting: No need to cast data from object to the expected type as you do with ViewData or ViewBag.
  • Separation of Concerns: It enforces a clear contract between the Controller and View about what data is expected.
How Do We Create a Strongly Typed View in ASP.NET Core MVC?

Creating a strongly typed View involves the following steps:

  • Create the Model Class: Define a model class representing the data you want to display in the view. This class contains properties corresponding to the data you need to access and render in the view.
  • Pass the Model Object from Controller: In your Controller action, create an instance of the model, populate it with data, and then pass it to the View.
  • Declare the Model Type in the View: At the top of the view file, declare the model type using the @model directive. This informs the view about the kind of data it will be working with.
  • Access Model Properties in the View: Inside the view, you can directly access the properties of the model using Razor syntax (@Model.PropertyName).
Example to Understand Strongly Typed View in ASP.NET Core MVC

Let’s understand how to create and work with a Strongly Typed View in an ASP.NET Core MVC application. We will be working with the same Student example.

Step 1: Define the Student Model

Before anything else, we need a model, a C# class that represents the data we want to display. The model acts as a blueprint for the data our view will use.

So, first, create a Student class inside the Models folder. This class acts as the data container that will be passed from the Controller to the View. This class has properties representing a student’s basic details. It is the model object that will be passed around.

namespace FirstCoreMVCWebApplication.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string? Name { get; set; }
        public string? Branch { get; set; }
        public string? Section { get; set; }
        public string? Gender { get; set; }
    }
}
Step 2: Modify the Controller to Pass Model to View

To create a Strongly Typed View in ASP.NET Core MVC, the Controller base class provides the following two overloaded versions of the View() extension method, which we can use to pass the model object from the controller action method to a view.

Example to Understand Strongly Typed View in ASP.NET Core MVC

Now, we will use the overloaded version of the Views() Extension method, which takes only the model object as an input parameter. So, please modify the HomeController as follows. Here, we create an instance of the Student model and pass it directly to the view.

using FirstCoreMVCWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Details()
        {
            //Using ViewBag
            ViewBag.Title = "Student Details Page";

            //Using ViewData
            ViewData["Header"] = "Student Details";

            //Creating Student Object to Hold Student data
            Student student = new Student()
            {
                StudentId = 101,
                Name = "James",
                Branch = "CSE",
                Section = "A",
                Gender = "Male"
            };

            // Pass the student model instance directly to the View
            return View(student);
        }
    }
}
Code Explanations:
  • The student object is created and filled with data.
  • The student object is passed as a parameter to the View(student) method. The return View(student) statement sends the entire student object to the view.
  • This makes the View strongly typed to the Student class.
  • We also still pass the Title and Header using ViewBag and ViewData.
Step 3: Create a Strongly Typed View

To create a strongly typed view in an ASP.NET Core MVC Application, we need to specify the model type within the view using the @model directive. Here, the Student class serves as our model, which we pass from our action method as a parameter to the View Extension method. Therefore, we need to specify the model for the view as follows.

@model FirstCoreMVCApplication.Models.Student

The above statement indicates that we will use FirstCoreMVCApplication.Models.Student as the model for this view. Please note that in the directive (@model), m is in lowercase, and the statement should not be terminated with a semicolon.

Then, to access the model object properties, we need to use @Model. Here, the letter is in uppercase. In our example, we can access the Student object properties, such as Name, Gender, Branch, and Section, by using @Model.Name, @Model.Gender, @Model.Branch, and @Model.Section, respectively. So, please modify the Details.cshtml view file as shown below to make the view a Strongly Typed View.

@{
    Layout = null;
}
<!DOCTYPE html>
@model FirstCoreMVCWebApplication.Models.Student

<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <h1>@ViewData["Header"]</h1>
    <div>
        StudentId : @Model?.StudentId
    </div>
    <div>
        Name : @Model?.Name
    </div>
    <div>
        Branch : @Model?.Branch
    </div>
    <div>
        Section : @Model?.Section
    </div>
    <div>
        Gender : @Model?.Gender
    </div>
</body>
</html>
Code Explanation:
  • The @model directive tells Razor that this view expects a Student object.
  • Inside the HTML, @Model.PropertyName allows you to access student properties directly, with full IntelliSense and type safety.
  • You don’t need to cast or use dynamic properties. Mistakes (like @Model.Nmae) will be caught at compile time.
  • You can still use ViewBag or ViewData for page-level info (like title), but the main content comes from the model.
Step 4: Run the Application

Now, run the application and navigate to the “/Home/Details” URL. You will then see the data as expected, as shown in the image below.

Strongly Typed View in ASP.NET Core MVC Application

In our example, we still use ViewBag and ViewData to pass the Header and Title from the Controller action method to the View. Then, the question that comes to your mind is how we will pass the Header and Title to a strongly typed view. In such scenarios, we need to use a view-specific model called View Model.

Strongly Typed Views are the preferred way to pass data from controllers to views in ASP.NET Core MVC. While ViewBag and ViewData offer flexibility, they lack compile-time safety and clarity. This is where Strongly Typed Views shine, making your code clean, type-safe, maintainable, and less error-prone.

In our next article, I will discuss the View Model in an ASP.NET Core MVC Application with Examples. In this article, I explain Strongly Typed Views in ASP.NET Core MVC applications. I hope you enjoy this article. 

2 thoughts on “Strongly Typed View in ASP.NET Core MVC”

Leave a Reply

Your email address will not be published. Required fields are marked *