ASP.NET CORE Mvc Strongly Typed View

In this tutorial will discuss strongly typed view in asp.net core mvc. strongly typed view in mvc is another data passing technique from controller to view.

Strongly Type View

The view which binds to a specific type of ViewModel is called as Strongly Typed View. By specifying  the model, once we define the  the Visual studio provides the intellisense and compile time checking of type.

Strongly Type View Configuration

The strongly typed Views are created using the @model directive and 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 View()  extension method which we can use to pass the model object from the controller action method to a view.

public virtual ViewResult View(string viewName, object model);
public virtual ViewResult View(object model);

In our student controller will return view with model object overloaded method and pass student information from controller to view.

public class StudentController : Controller
{
protected readonly IStudentRespository _studentRespository;
public StudentController(IStudentRespository studentRespository)
{
_studentRespository = studentRespository;
}

public ViewResult Details(int id)
{
Student student = _studentRespository.GetStudent(id);
return View(student);
}
}

 Suppose you already have view and you want make strongly type then we need to specify model using @model directive for example in Details.cshtml we need to make changes and below into the Details.cshtml.

 @model SampleProjectCore.Student

Now we can access the model properties simply by using @Model, here the letter M is in uppercase. So, in our example, we can access the Student information object properties.

Important features of Strongly Typed Views :

      • Automatic scaffolding:Creates view with skeleton based on selected Template and Model.
      • IntelliSense support :Visual Studio able to display IntelliSense using the Model.
      • Compile time type checking: We will get compiler error rather than a runtime error.

You can watch our video version of this tutorial with step by step explanation.