Before reading this I would request you to go through previous articles on ASP.NET MVC:
I hope the above articles are clear by now. Let us start with the application. Open Visual Studio. Go to File->New->Project. Give a suitable name to the application. Click OK.
Select Empty Template. Click OK.
Now our application is created. We have a very basic MVC structure in the application with primarily three folders: Model, View and Controller.
Let us add a class in the Model folder. Right click on Model folder. Go to Add->Class. I have named it Student.cs.
Let us add few basic properties to our model now.
- public class Student
- {
- publicintStudentID
- {
- get;
- set;
- }
- public string Name
- {
- get;
- set;
- }
- publicint Marks
- {
- get;
- set;
- }
- public string City
- {
- get;
- set;
- }
- }
Now we will add a Controller. Right click on Controller. Add->Controller.
Select MVC 5 Empty Controller. Click Add.
We will give a suitable name to the controller. Click Add once name is assigned.
Let us write some code in the controller class.
- usingMVCPassDatafromModel.Models;
- using System;
- usingSystem.Collections.Generic;
- usingSystem.Linq;
- usingSystem.Web;
- usingSystem.Web.Mvc;
- namespaceMVCPassDatafromModel.Controllers
- {
- public class GetDetailsController: Controller
- {
-
- publicActionResultGetStudents()
- {
- List < Student > Objstud = new List < Student > ()
- {
- new Student
- {
- StudentID = 1, Name = "Nitin Tyagi", Marks = 90, City = "New Delhi"
- },
- new Student
- {
- StudentID = 2, Name = "AbhijeetSingh", Marks = 80, City = "Hyderabad"
- },
- new Student
- {
- StudentID = 3, Name = "Arjun Singh", Marks = 90, City = "Jaipur"
- },
- };
- return View(Objstud);
- }
- }
- }
We have defined a List of Students and populated it with data. We would be passing this data to the View. Since we do not have a views we will create a View. Right click on GetStudents() method. Go to Add->View. Select the empty template. Click Add.
Write the following Razor code in GetStudents.cshtml.
- @modelIEnumerable < MVCPassDatafromModel.Models.Student >
- @
- {
- Layout = null;
- }
-
- <!DOCTYPE html >
- <html >
- <head >
- <meta name = "viewport" content = "width=device-width" / >
- <title > GetStudents < /title>
-
- </head>
- <body >
- <div >
- <h2 > Student List < /h2>
- @foreach(vari in Model)
- {
- < p > @i.StudentID | @i.Name | @i.Marks | @i.City < /p>
- }
- </div>
-
- </body>
-
- </html>
We have used a foreach loop to iterate the model that we have passed from the controller. For this purpose we have used the following markup to create a strongly typed view.
@modelIEnumerable<MVCPassDatafromModel.Models.Student>
Let us run the application now and see the output.
We have our data displayed in the view. This is how we can display data from controller to view.