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. What is a Strongly Typed View in ASP.NET Core MVC?
  2. Why do we need a Strongly Typed View in ASP.NET Core MVC?
  3. How do We Create a Strongly Typed View in ASP.NET Core MVC?
What is a Strongly Typed View in ASP.NET Core MVC?

A Strongly Typed View in ASP.NET Core MVC is associated with a specific class, known as a view model. This class defines the data and behaviors the View needs to display or interact with. It is a view that expects a specific data model to be passed to it from the controller action method.

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 intellisence support or compile-time error checking in a loosely typed view. With a Strongly Typed View, we will get the following benefits:

  • Type Safety: By specifying the model type, we get compile-time type checking, which helps prevent runtime errors due to type mismatches. With a strongly typed view, the compiler checks that the view is using properties and methods that exist on the view model class.
  • Intellisense Support: IDEs like Visual Studio provide intellisense for the model properties, which provides auto-completion of model property names, improving development speed and reducing errors.
  • Refactoring Support: Refactoring becomes easier and safer; for example, renaming a property on a model will automatically indicate places in views where changes are needed.
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 method, 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: You can access the model’s properties inside the view using Razor syntax (@Model.PropertyName). Here, you will get the intellisence support for the model properties.
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

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 using the @model directive. Here, the Student class will be our model, 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 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 is 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

In our example, we still use ViewBag and ViewData to pass the Header and Title from the Controller action method to the View. Then definitely, 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.

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. 

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 *