In the first tutorial we showed you how to create a controller and in the second tutorial, we showed how to add a view to your project. Here is the link to those tutorials.
- Create ASP.NET MVC Application
- Create ASP.NET MVC Application -Adding View.
- Create ASP.NET MVC Application – Add CRUD Functionality
In this tutorial, we will show you how to add a model to the project.
Table of Contents
Create ASP.NET MVC Application -Adding model
What is a Model
Model is a class which represents the data. It is the responsibility of the model to fetch data from the data store and return it to the controller. It should contain the validation logic, business logic, which operates on the data. Model is M part of the MVC Design pattern. Read about MVC Design pattern from this link Let us add a model to represent the customer with fields CustomerName, Address and country to our project.
How to Add a Model
In MVC models are stored in the Model folder.
- Select the Model folder
- Right Click and select Add
- Click on Class This will open the add new item
- Enter the Name of Class as Customer
- Click on Add This Will Create a customer class in the model folder as shown in the image below
- Add the following code in the customer class as shown In the image above.
1 2 3 4 5 6 7 8 9 10 11 | public class Customer { [Key] public int id { get; set; } public string CustomerName { get; set; } public string Address { get; set; } public string Country { get; set; } } |
- Note that the key attribute is added to the property id. This is to indicate the MVC that the id is the primary key.
- Import the namespace ComponentModel.DataAnnotations as shown in the diagram.
Data for the Model
In real life situations data for the model comes from the database. The very popular way of getting data is to use the entity model. For this tutorial we will keep it simple. We will imitate the database connection in our code. To this add the following code to the customer class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | Â public class OurDatabase { List _Customers; public List Customers{ get{ _Customers = new List(); _Customers.AddRange(new[] { new Customer { id = 1, CustomerName = "Microsoft", Address = "Redmond, WA", Country = "USA" }, new Customer { id = 2, CustomerName = "Google", Address = "Mountain View, CA, ", Country = "USA" }, new Customer { id = 3, CustomerName = "Infosys", Address = "Bengaluru, Karnataka", Country = "USA" } }); return _Customers; } set { _Customers = value; } } } |
What we have done here is created a Class OurDatabase. It has one property Customers which is a collection of our model customer. In its get method, we populate customers collection with the dummy data. In real situations, this is populated from the database.
Add a Controller
We already have HomeController in our Project. Let us create another empty controller and name it as CustomerController. I will leave this exercise to you. You can refer to our first tutorial How to Create MVC Application – Part I The Index Action Method is automatically added to the Project by Visual Studio. Rename it as List.
1 2 3 4 5 6 | public ActionResult List() { return View(); } |
Add a View
We showed you how to create a view in our last tutorial. Last time we created an empty View. This time we use our model customer to generate the view. Follow these steps
- Right-click anywhere in the action method List in Customer Controler
- Click Add View This will bring Add View dialogue box
- Keep the name of the view as it is. MVC Convention requires that the Action Method Name and View name must match.
- From the template drop down select the Template List. The List template Displays the Customer in the Grid format.
- From the Model class drop-down shows the customer model, which we had created. Select it.
- Uncheck all the other options as shown in the image above.
- Click on Add to create the view
View List.cshtml is created under the folder Customer, which is under the folder Views Open the View and you will see that the visual studio has generated the codes for us.
Look at the View
Browse to the Views->Customer->List.html and open it. You will see that the visual studio has generated the code for us. Lets us look at the code
1 2 3 | @model IEnumerable<MVCHelloWorld.Models.Customer> |
The controller needs to pass the model to the view so the view can display the data from the model to the user. This is done using @model keyword. Here @model keyword indicates that the view is expecting a Customer object.
1 2 3 4 5 6 7 | @{ Layout = null; } |
Master layout page to be used for the View. We are not using any layout page.
1 2 3 4 5 | @Html.ActionLink("Create New", "Create") |
@html.ActionLink is an HTML helper method. It renders an HTML link. It will create a link to a controller action. The above code is translated to the following HTML snippet. <a href=”/Customer/Create”> Create New </a> Clicking on Create New will result in calling Create Action method in the Customer Controller The next code creates a simple HTML Table to display the List of customers
1 2 3 4 5 6 7 | @Html.DisplayNameFor(model => model.CustomerName) @Html.DisplayNameFor(model => model.Address) @Html.DisplayNameFor(model => model.Country) |
The table heading uses another HTML helper method call Html.DisplayNameFor, Which Gets the display name for the model.
1 2 3 | @foreach (var item in Model) |
Model is the strongly typed object of our model Customers which is the collection of cu the tomer object. The above code loops through each customer collection
1 2 3 4 5 6 7 | @Html.DisplayFor(modelItem => item.CustomerName) @Html.DisplayFor(modelItem => item.Address) @Html.DisplayFor(modelItem => item.Country) |
@Html.DisplayFor is another HTML helper. It generates the required HTML output based on the property’s type.
1 2 3 4 5 6 7 | @Html.ActionLink("Edit", "Edit", new { id=item.id }) | @Html.ActionLink("Details", "Details", new { id=item.id }) | @Html.ActionLink("Delete", "Delete", new { id=item.id }) |
Here @html.Actionlink generates Edit, Details and Delete action link which calls the corresponding controller action. Note that it used the third parameter which is id of each customer.
Pass model to the View
Open the CustomerController . Now we have to pass our model to the View from the index Action Method. Copy the following code to the Index Action Method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public ActionResult Index() { OurDatabase DB = new OurDatabase(); List Customers; Customers = DB.Customers; return View(Customers); } |
- DB is now an instance of the OurDatabase which imitates the database connection.
- Customers is an instance of the Collection of Customers.
- From DB we get the list of customers.
- Pass the customers to the View.
Run the Project
Now we are ready to test our project. Run the Project Enter Customer in the URL and you will see the list of customers in your browser.
Conclusion
We have learned how to create a model and pass the model to the view via controller. Models gets their data from the database. But in our tutorial we did not create any database connection for the sake of simplicity. In the Next Tutorial we will show you how to create Add /Edit/Delete functionality to our project. If you have any queries feel free to use our comments section. Please don’t forget to share the page in your facebook wall.
Links to other tutorials
- Create ASP.NET MVC Application
- Create ASP.NET MVC Application -Adding View.
- Create ASP.NET MVC Application – Add CRUD Functionality