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 ASP.NET Core MVC Application with Examples. Please read our previous article discussing ViewBag in ASP.NET Core MVC Application. As part of this article, we will discuss the following pointers.

  1. Why do we need a Strongly Typed View in ASP.NET Core MVC?
  2. How do you create a Strongly Typed View in ASP.NET Core MVC?
  3. What are the Advantages of using a Strongly Typed View?
  4. When should you use a Strongly Typed View in ASP.NET Core MVC?
Why do we need a Strongly Typed View in ASP.NET Core MVC?

As we already discussed, in ASP.NET Core MVC, we can pass the model data to a view using many different methods, such as ViewBag, ViewData, TempData, Strongly Typed View Model, etc. The view becomes loosely typed when we pass the model data to a View using ViewBag, TempData, or ViewData. We will not get intelligence support or compile-time error checking in a loosely typed view. 

A strongly typed view in ASP.NET Core MVC is a view specifically designed to work with a particular type of model. This model is passed from the controller to the view, allowing for direct interaction with the data structure. The compiler provides Type-Checking and IntelliSense support for the data being used in the view. Strongly typed views enhance code quality, reduce runtime errors, and improve maintainability by ensuring that the data used in the view aligns with the expected data structure.

How Do We Create Strongly Typed Views in ASP.NET Core MVC?

To create a strongly typed view in ASP.NET Core MVC, we need to follow the below steps:

  1. Create a Model: 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.
  2. Pass the Model to the View: In the controller action, create an instance of the model class, populate it with data, and then pass it to the view.
  3. Declare the Model in the View: At the top of the view file, declare the model type using the @model directive. This informs the view about the type of data it will be working with.
  4. Access Model Properties in the View: Inside the view, you can access the properties of the model using Razor syntax (@Model.PropertyName). The compiler provides IntelliSense support for the properties of the model, helping you avoid typos and access properties safely.
Example to Understand Strongly Typed View in ASP.NET Core MVC Application
Create a Model

First, you need to define a model class. A model is a C# class with properties. This class will be used to transfer data between your controller and view. We will use the same application we used in our previous two articles. So, we are going to use the same Student model. If you are coming to this article directly without reading our previous two articles, then please create the following Student class within the Models folder:

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; }
    }
}

To create a Strongly Typed View from the controller’s action method, we must pass the model object as a parameter to the View() extension method. 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 in the ASP.NET Core MVC Application.

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

We will use the example we worked on in our previous two articles. Now, we will use the overloaded version of the Views() Extension method, which takes only the model object as an input parameter. So, modify the Details action method of the Home Controller, as shown below, to pass the student object as a parameter to the View extension method. 

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"
            };

            //Passing the Model Object as a Parameter to View Extension Method
            //It means the View is going to be a Strongly Type View for the Student Model
            return View(student);
        }
    }
}
Changes in Details.cshtml View:

To create a strongly typed view in the ASP.NET Core MVC Application, we need to specify the model type within the view by using the @model directive. Here, the Student class will be our model, which we passed from our action method as a parameter to the View Extension method. So, we need to specify the model for the view, as shown below.

@model FirstCoreMVCApplication.Models.Student

The above statement will tell the view that we will use FirstCoreMVCApplication.Models.Student as the model for this view. 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, you can use @Model. Here, the letter M is in uppercase. So, in our example, we can access the Student objects properties such as Name, Gender, Branch, and Section by using @Model.Name, @Model.Gender, @Model.Branch, and @Model.Section, respectively. So, 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>

Now run the application and navigate to the /Home/Details URL. As shown in the image below, you will see the data as expected.

Strongly Typed Views in ASP.NET Core MVC

Advantages of Using Strongly Typed Views: 

We will get the following advantages when we use a strongly typed view.

  1. It will provide Compile-Time Error checking, and we will get intelligence support.
  2. With intelligence support, the chances of mis-spelling the properties and making typographical errors are almost zero.
  3. If we misspell the property name, it comes to know at compile time rather than runtime.

The best and preferred approach in ASP.NET Core MVC to passing data from a controller action method to a view is to use a strongly typed model object. Using strongly typed views promotes code correctness, makes your code more readable, and helps catch errors at compile time rather than runtime. 

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

1 thought on “Strongly Typed View in ASP.NET Core MVC”

Leave a Reply

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