How to create strong type view in MVC appllication
Create strong type view in MVC application
In this quick article we will learn how to create strong
type view in MVC application. There is little advantage in strong type view. We
can send data in form of object. Let’s implement strong type view with small
example.
Create simple model
Open one empty MVC application and add below model into it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVCTest.Models
{
public class Person
{
public String Name{ get; set; }
public String Surname { get; set;
}
public String Age
{ get; set; }
}
}
Our model is very simple, only we have implemented Person classes
which contain three properties.
Create Person Controller
Let’s create one controller to handle model data. As we have
defined our model class name as Person. We will define controller name as
PersonController. Have a look on below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTest.Models;
namespace MVCTest.Controllers
{
public class PersonController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetData(Person objP)
{
String Name = objP.Name;
String Surname = objP.Surname;
Int32 Age = Convert.ToInt32(objP.Age);
return Content("Name:-" + Name + " Surname:-" + objP.Surname + " Age:-" +
objP.Age);
}
}
}
The controller contains tow actions. Index action will show
HTML form, and GetData() function will call when we sill submit form.
Create strong type view
Now we will create strong type view. The advantage of strong
type view is we can send and receive data in the form of object. To create
strong type view, just right click on Index action, you will see below form.

Now,
add below code in view
@model MVCTest.Models.Person
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@using
(Html.BeginForm("Person", "GetData", FormMethod.Post))
{
@Html.LabelFor(m=>m.Name)
@Html.TextBoxFor(m=> m.Name)
@Html.LabelFor(m=>m.Surname)
@Html.TextBoxFor(m => m.Surname);
@Html.LabelFor(m => m.Age)
@Html.TextBoxFor(m => m.Age);
<input type="submit" name="Submit" value="submit" />
}
</div>
</body>
</html>
Have a look on first line of View. We are pointing Person
class as model. And as it is strong type view, we can use lamda expression
to point each property of model class.
Output:-
Conclusion:-
In this article we have learned how to create strong type view in MVC application.