Download source code here…
Description: In this article, we will learn the basics of ASP .NET MVC with the help of an example.
MVC – It stands for Model View Controller. It’s a very easy concept. Let’s understand this in a detail.
- A controller can send commands to the model to update the model’s state (e.g., editing a document). It can also send commands to its associated view to change the view’s presentation of the model (e.g., by scrolling through a document). It is an intermediate between the model and the view. It is usually a class (.cs) file.
- A model stores data that is retrieved to the controller and displayed in the view. Whenever there is a change to the data it is updated by the controller. Actually, it is made to create the Business Logic. It is a class (.cs) file.
- A view requests information from the model that it uses to generate an output representation to the user. It is a file with extension (.cshtml).
- A view uses an engine called Razor View Engine. It is actually used to embed C# code in a HTML page. To use C# code in View page, prefix (@) symbol.
Let’s understand the above theory with the help of an example.
Step 1: Create an Empty ASP.NET MVC application in Visual Studio.
Step 2: You will see that Model, View, and Controller folders will be automatically created in the Solution Explorer.
Step 3: Add a model class file to the models folder. Name it as Employee.cs.
Step 4: Create the auto-implemented properties inside it. Simply paste the below code.
Step 5: Add a controller to the Controllers folder that will use the above created model class.
Step 6: Copy the below code to use the model class’s property inside the controller.
In this code, a namespace is added to use the model class. We just created the instance of the class Employee and initialized its properties. Then we returned that instance to the View because, we will show this data on the View page. So, view will show the data contained in this instance.
Step 7: Right click on the GetDetails method and add a View.
Remember to build the project through solution explorer otherwise, Model class in the above screenshot will not be available in the dropdown menu.
Step 8: A view will be added to the Views folder.
Step 9: Add the following code to GetDetals.cshtml.
Step 10: Just press F5 and Navigate to the URL.
In the above URL, Employee is the Name of Model and GetDetails is the name of View that is included in this model. This View searches for GetDetails method in Controller. If it finds it in the controller, then data will be shown otherwise 404 error will occur. So, please be sure that the Name of view and function in controller is same.
See this article at C-SharpCorner…