Strongly Typed View in ASP.NET Core MVC

Strongly Typed View in ASP.NET Core MVC Application

In this article, I am going to discuss How to Create a Strongly Typed View in ASP.NET Core MVC Application with Examples. Please read our previous article, where we discussed ViewBag in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers.

  1. Why do we need a Strongly Typed View in ASP.NET Core MVC?
  2. How to Create a Strongly Typed View in ASP.NET Core?
  3. What are the Advantages of using a Strongly Typed View?
Why do we need a Strongly Typed View in ASP.NET Core MVC?

In ASP.NET Core MVC, as we already discussed, we can pass the model data to a view using many different ways, 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 or ViewData. In a loosely typed view, we will not get any intelligence support as well as the compile-time error. With a Strongly Typed View, we will get both intelligence support as well as compile-time error checking.

In ASP.NET Core MVC, a strongly typed view is a view that is strongly associated with a specific data type or model class. This means that the view is designed to work with a particular type of data, and the compiler provides type-checking and IntelliSense support for the data being used in the view. Strongly typed views are a way to 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 to Create a Strongly Types View in ASP.NET Core MVC?

To create a strongly typed view in ASP.NET Core MVC, you typically follow these steps:

  1. Create a Model: Define a model class that represents the data you want to display in the view. This class contains properties that correspond 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

In order to create a Strongly Typed View from the controller’s action method, we need to pass the model object as a parameter to the View() extension method. The Controller base class provides us 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 work with the same example we worked on in our previous two articles. Now, we are going to 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:

In order to create a strongly-typed view in ASP.NET Core MVC Application, we need to specify the model type within the view by using the @model directive. Here, the Student class is going to 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 are going to use FirstCoreMVCApplication.Models.Student as the model for this view. You need to remember that here in the directive (@model), m is in lowercase, and the statement should not be terminated with a semicolon.

Then in order 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, and you will see the data as expected, as shown in the below image.

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, as well as 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 pass data from a controller action method to a view is by using 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. It’s considered a best practice in ASP.NET Core MVC development.

In our example, we are still using 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. Well, in such scenarios, we need to use a view-specific model called View Model.

In our next article, I am going to discuss the View Model in ASP.NET Core MVC Application with Examples. Here, in this article, I try to explain the Strongly Typed View in 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 *