How to implement strongly typed view in MVC4.0?
We can pass data from controller to view by using various ways. Strongly typed view is one of the way through which information can be carried out. In this article, I have explained how to do implementation of strongly typed view in razor MVC4.0 application.
Description: If you are comfortable in Razor in MVC4.0, model property is available which is dynamic. You do not need to know the exact type but can access the value.
Viewbag is also one way to pass information from controller to view which is alternative for strongly typed view. Another way is to do with the help of using @model dynamic.
strongly typed view implementation:
How to declare model name in view?
Model name can be mentioned by @model modelname. Lets take an example by creating class ClsEmployee.cs as follows:
Public class ClsEmployee
{
public string EmployeeFirstName { get ; set ; }
public string EmployeeLastName { get ; set ; }
public string EmployeeAddress { get ; set ; }
}
If you use ViewData.Model then it can be as follows:
@var emp = (ClsEmployee) ViewData.Model; }
But this ViewData.Model can be eliminated by using strongly types view. Please make sure that all references to ViewData.Model will be strongly typed and it will be directly accessible by using following:
@model ClsEmployee
<h1>@Model.EmployeeFirstName </h1>
<div> @Model.EmployeeLastName </div>
<div> @Model.EmployeeAddress </div>