- In this tutorial, we will teach you how to
create Model and how to displaying view model data in view.
- Lets first Create New ASP.Net MVC Application
with Basic Template and Name it to “ViewModelDemo”.
How to Create Model?
Right click on Models folder ⇒
Add ⇒ Class ⇒ Name it Person.cs ⇒
click “Add”.
After adding Model class add following code :
namespace ViewModelDemo.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Degree { get; set; }
}
}
Now Add controller "HomeController" and view "Index" appropriate :
using ViewModelDemo.Models;
namespace ViewModelDemo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var person = new Person
{
Id = 1,
Name = "Manav Pandya",
Degree = "M.C.A"
};
return View("Index",
person);
}
}
}
- In above code, we will create person variable or object
from Person class with some data. Before create views you must build the
project.
Strongly typed
views
- Now Create View by right click on Index action
⇒ Add View ⇒ check the
“”Create a strongly-typed view and select Person Model and Leave it all
configuration ⇒ click “Add”.
@model
ViewModelDemo.Models.Person
@{
ViewBag.Title
= "Index";
}
<h2>Index</h2>
<h1>@Model.Name</h1>
<p>@Model.Degree</p>
- Now,
run the project and browse the Index action of HomeController, you will get
preview as shown in below screenshot.
Final Output :
Thanks , I hope you like above Article
You may also Like :
ASP.NET , MVC , What is ASP.NET MVC ? , Razor , AngularJs , Bootstrap , Visual Studio , Model View Controller