Simple Example to Illustrate Concept of MVC

I have Taken a Model named Student.cs.

This Student class contain all the properties that is required to display Student Details.
  1. public class Student {  
  2.     public int StudentID {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string RollNo {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string DOB {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public Student() {  
  19.         this.Name = string.Empty;  
  20.         this.RollNo = string.Empty;  
  21.         this.DOB = string.Empty;  
  22.     }  

After that i have added a controller that will have a controller Method name "Details".

Inside that we will add a view named "Details" and by default the view and Controller Method will have same Name. while adding View it is advisable to use Strong Naming Convention. 
  1. public class EmployeeController: Controller {  
  2.     public ActionResult Details() {  
  3.         Student std = new Student() {  
  4.             StudentID = 101,  
  5.             Name = "Harsh",  
  6.             RollNo = "10800038",  
  7.             DOB = "10/06/1990"  
  8.         };  
  9.         return View(std);  
  10.     }  

The Code inside view will Look like this. the Extension of a view is ".cshtml"
 
The code inside view will look like this. 
  1. @model MVCStudentDemo.Models.Student  
  2. @{  
  3. ViewBag.Title = "Student Details";  
  4. }  
  5.   
  6. <h2>Student Details</h2>  
  7. <table style=>  
  8.     <tr>  
  9.         <td>  
  10. Student ID :  
  11. </td>  
  12.         <td>  
  13. @Model.StudentID  
  14. </td>  
  15.     </tr>  
  16.     <tr>  
  17.         <td>  
  18. Student Name :  
  19. </td>  
  20.         <td>  
  21. @Model.Name  
  22. </td>  
  23.     </tr>  
  24.     <tr>  
  25.         <td>  
  26. Student Roll# :  
  27. </td>  
  28.         <td>  
  29. @Model.RollNo  
  30. </td>  
  31.         <tr>  
  32.             <td>  
  33. Student DOB :  
  34. </td>  
  35.             <td>  
  36. @Model.DOB  
  37. </td>  
  38.         </tr>  
  39.     </tr>  
  40. </table> 
Note: In web form application the URL are mapped to Physical Files and in MVC application the URL are mapped to Controller Action Methods.

The controller responds to the URL requests, gets data from Model and hands it over to VIew. the view then renders the Data. Models can be entities or data Object
 
 
When we will type the following URL.

"http://localhost:58783/Employee/Details
".

You just have to append the Controller and  Controller method name into your URL. 
 
After rendering the Output will look like this.



If you need the Solution please drop me a message.
Ebook Download
View all
Learn
View all