Use Business Library as Model in ASP.Net MVC

Here we will understand models with a different library, in other words In MVC. When we run an application we need to specify the correct controller name with an Action method. If we pass the wrong name then it gives an error.
 
But with a model this is different, in other words a model is optional and we can put it anywhere a library can be put.
 
Step 1
 
Create a database table, so for that execute the following code:
  1. Create Table StudentInfo (  
  2. StudentID int identity primary key,  
  3. StudentName nvarchar(50),  
  4. Gender nvarchar(50),  
  5. SchoolName nvarchar(50)  
  6. ) GO Insert into StudentInfo  
  7. values  
  8. ('Munesh''Male''VIT'Insert into StudentInfo  
  9. values  
  10. ('Rahul''Male''ABC'Insert into StudentInfo  
  11. values  
  12. ('Reet''Female''XYZ'Insert into StudentInfo  
  13. values  
  14. ('Anshuman''Male''PQR')  
Also create a Stored Procedure for retrieving data from the database.
  1. Create procedure GetAllStudents as Begin  
  2. Select  
  3. StudentID,  
  4. StudentName,  
  5. Gender,  
  6. SchoolName  
  7. from  
  8. StudentInfo End  
Step 2
 
Now add a new library to the solution. So for adding a library to the solution, right-click on the project in the Solution Explorer then select Add -> New Project.
 
Then the New Project screen will be shown. From that screen we will select "Windows" -> "Class Library" and provide this library a meaningful name such as “BusinessLayer”.
 
This automatically generates a class such as “Class1.cs”, so change the class name to “Student.cs” and define the database property as we defined in the model classes.
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace BusinessLayer {  
  6.     public class Student {  
  7.         public int StudentID {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string StudentName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Gender {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string StudentClass {  
  20.             get;  
  21.             set;  
  22.         }  
  23.     }  
  24. }  
Step 3
 
Add a another class to this library for writing the business logic code and using that we will retrieve the data from the database. Provide this class the name “BusinessLogic.cs”.
 
Before writing the code for retrieving the data from the database, first add some references for ADO.Net to this library. Go to the references folder of this library project  then right-click on the References folder then select .Net then select "System.Configuration" assembly. Then provide the following code for the class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Configuration;  
  8. namespace BusinessLayer {  
  9.     public class BusinessLogic {  
  10.         public IEnumerable < Student > student {  
  11.             get {  
  12.                 string connectionString = ConfigurationManager.ConnectionStrings["Conncet"].ConnectionString;  
  13.                 List < Student > employees = new List < Student > ();  
  14.                 using(SqlConnection con = newSqlConnection(connectionString)) {  
  15.                     SqlCommand cmd = new SqlCommand("GetAllStudents", con);  
  16.                     cmd.CommandType = CommandType.StoredProcedure;  
  17.                     con.Open();  
  18.                     SqlDataReader rdr = cmd.ExecuteReader();  
  19.                     while (rdr.Read()) {  
  20.                         Student student = new Student();  
  21.                         student.StudentID = Convert.ToInt32(rdr["StudentID"]);  
  22.                         student.StudentName = rdr["StudentName"].ToString();  
  23.                         student.Gender = rdr["Gender"].ToString();  
  24.                         student.StudentClass = rdr["SchoolName"].ToString();  
  25.                         employees.Add(student);  
  26.                     }  
  27.                 }  
  28.                 return employees;  
  29.             }  
  30.         }  
  31.     }  
  32. }  
After all that is done build the library project.
 
The connection string in the web config will be:
  1. < connectionStrings > < add name = "Connect"  
  2. connectionString = "server=.; database=MVCApplication; integrated security=SSPI"  
  3. providerName = "System.Data.SqlClient" / > < /connectionStrings>  
Step 4
 
Now go to your MVC project and add the reference for the library project, using right-click on the References folder.
 
 
 
Step 5
 
Now go to the controller folder and add a controller to this project. Provide the name for this controller as “Student”. In this controller add the namespace for the BusinessLogic project.
 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using BusinessLayer;  
  7. namespace MvcApplication2.Controllers {  
  8.     public class StudentController: Controller {  
  9.         public ActionResult Index() {  
  10.             BusinessLogic BL = new BusinessLogic();  
  11.             List < Student > student = BL.student.ToList();  
  12.             return View(student);  
  13.         }  
  14.     }  
  15. }  
Step 6
 
Now right-click on this Controller method and add a view. When creating the view select the Model class as “Student” and provide a Scaffold template as “List” so it will create a list for us.
 
  1. @model IEnumerable  
  2. <BusinessLayer.Student>  
  3. @{  
  4. ViewBag.Title = "Index";  
  5. }  
  6.   
  7.     <div>  
  8.         <h2>Index</h2>  
  9.         <p>  
  10. @Html.ActionLink("Create New", "Create")  
  11. </p>  
  12.         <table border = "1">  
  13.             <tr>  
  14.                 <th>  
  15. @Html.DisplayNameFor(model => model.StudentName)  
  16. </th>  
  17.                 <th>  
  18. @Html.DisplayNameFor(model => model.Gender)  
  19. </th>  
  20.                 <th>  
  21. @Html.DisplayNameFor(model => model.StudentClass)  
  22. </th>  
  23.                 <th>  
  24. Action To be Taken  
  25. </th>  
  26.             </tr>  
  27. @foreach (var item in Model) {  
  28.   
  29.             <tr>  
  30.                 <td>  
  31. @Html.DisplayFor(modelItem => item.StudentName)  
  32. </td>  
  33.                 <td>  
  34. @Html.DisplayFor(modelItem => item.Gender)  
  35. </td>  
  36.                 <td>  
  37. @Html.DisplayFor(modelItem => item.StudentClass)  
  38. </td>  
  39.                 <td>  
  40. @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |  
  41. @Html.ActionLink("Details", "Details", new { id=item.StudentID }) |  
  42. @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })  
  43. </td>  
  44.             </tr>  
  45. }  
  46.   
  47.  </table>  
  48. </div>  
Before running this application change the controller name in the Route.config file.
  1. public static void RegisterRoutes(RouteCollection routes) {  
  2.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  3.     routes.MapRoute(  
  4.     name: "Default",  
  5.     url: "{controller}/{action}/{id}",  
  6.     defaults: new {  
  7.         controller = "Student", action = "Index", id = UrlParameter.Optional  
  8.     });  
  9. }  
Now run the application and you will get output like this:
 

Here if you will click on any link it will give am exception because we didn't work on the links.
 
You can go to my_blog.


Similar Articles