Introduction
So far, we have used Entity Framework and entities, which are mapped to the database tables, and object relational mapping tools like Entity Framework, nHibernate etc., which are used to retrieve and save the data.
Business objects contain both state (data) and behavior, which is the logic of being specific to the business.
In MVC, there are several conventions to be followed. Example- Controllers need to have a word controller in them and should implement IController interface either directly or indirectly. Views should be placed in a specific location, which MVC can find them as-
http://localhost/projectname/Home/Index
In this example, HomeController, look at the name as-
Here, it has the controller at the end of it and this HomeController is actually inheriting from Controller class, but it should implement IController interface. Now, here HomeController is indirectly inheriting from the IController interface. We will inspect that click on controller and go to definition as-
Controller class is inheriting from ControllerBase Class. Right click on it and go to Definition, as given below-
Notice the ControllerBase is getting inherited from IController interface, which means our HomeController class is indirectly inheriting from IController interface.
When it comes to views, we also have convention, the name of the views is important. Let’s understand practically with an example here.
In our MVC Application, we have our HomeController. Within it, we have Index action method. This index action method is invoked, when we type in URL as /home/Index.
Notice, we are not specifying the name of the view. How does MVC Application know what view it should return? This is where the convention comes into play. MVC Application is going to inside the controller for views. At the moment, I have a view, which is Index.cshtml
This is present within Views Folder of Home Folder. In Our View, we are looping the code, as given below-
Let’s run our solution and type /home/Index in our URL, as given below-
We got the desired output as expected. Now, I will rename it to Index1.cshtml, run our app and see the output, as given below-
You can see, when I try to navigate home/Index, we get this error. It’s actually looking for Index.aspx,ascx,.cshtml and so on. It’s basically looking for a view file either with name Index.aspx and so on in the Home folder and in the Shared Folder. So if it doesn’t find a View with those names and the locations, it’s going to throw this exception.
Due to this, the conventions are very important for Controllers and Views.
Note - In MVC, we can get rid of the Models Folder or we can delete the folder. In MVC Application, your Models can reside anywhere in the Application.
Now, we will add a ClassLibrary to our project.
Name it as a BusinessLayer.
In SQL Server, we will create a simple store procedure, which will retrieve the data as-
Now, we will assign get and set properties in an Employee Class, as given below-
Now, we will add another class file as EmployeeBusinessLayer in this class file. It will contain all the business logic. In this class, we will have some data access code, which will retrieve the code from the database table.
- publicclassEmployeeBusinessLayer {
- publicIEnumerable < Employee > Employees {
- get {
- stringconnectionString = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
- List < Employee > employees = newList < Employee > ();
-
- using(SqlConnection con = newSqlConnection(connectionString)) {
- SqlCommandcmd = newSqlCommand("spGetAllStudents", con);
- con.Open();
- SqlDataReaderrdr = cmd.ExecuteReader();
- while (rdr.Read()) {
- Employeeemployee = newEmployee();
- employee.id = Convert.ToInt32(rdr["id"]);
- employee.name = rdr["name"].ToString();
- employee.gender = rdr["gender"].ToString();
- employee.city = rdr["city"].ToString();
- employees.Add(employee);
-
- }
-
- }
- return employees;
-
- }
-
- }
- }
When you look at the code, its pretty straight forward one. We have a configuration manager class to read the connection string from our web.config file, as given below-
- <connectionStrings>
- <addnameaddname="Test" connectionString="Data Source=DESKTOP-QOMPPF7;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=***********" providerName="System.Data.SqlClient" />
- </connectionStrings>
Thus, we are reading the connection string as we want the list of employees. We had created an employee object, which will return the list of the employees and then we are building our SQLconnection object. We are executing SQL command and we are using our stored procedure to get the desired output. We are opening the connection and executing our command and then loop through each row. We are converting a row to employee object and with a employee object with a list and then we are returning employees .
Now, we will add a reference to our main project. We want to consume this Business Layer Library in our main project, so kindly add reference, as given below-
">
Now, we will add a controller and we will call this controller as EmployeeController.
Import the namespace of your BusinessLayer, as given below-
- publicclassEmployeeController: Controller {
- // GET: Employee
- publicActionResultIndex() {
- EmployeeBusinessLayeremployeeBusinessLayer = newEmployeeBusinessLayer();
- List < Employee > employees = employeeBusinessLayer.Employees.ToList();
- return View(employees);
- }
- }
As we want to return the list of employees, next step is to add a view.
Select Template as List and click Add. When you click Add, a view with index.cshtml creates under Employee folder inside Views folder.
In it, view a code, which has automatically created. Kindly add some styles and run the solution and you will see-
We had successfully retrieved the information from the database.
When you click Create New, it will give you an error, as given below-
Do we have an action method in Employee Controller as Create? NO, due to which it’s giving an error.