ASP.NET MVC 5 - First Web Application: Part 2

In my previous article ASP.NET MVC 5 - First Web Application: Part 1, I demonstrated how to develop a simple student registration form in MVC based web application. The only drawback of that application is that same data is not saved in the database. So we can’t get the student list from the database already saved. In this article, we will just expand the work to save the student registration data into the database and in the index page, populate the student list from database when view is loading. 

For doing this, we need to create two new projects in the same solution.

Create project for the model structure
 
For this click on File, New, then Project and select Class Library project. After that provide the project name MVCDataModel and click on OK button.

table 
 
Similarly, we create another class library projects name  MVCDataService. The purpose of this class is to communicate with the database objects for database operations.
 
Now first thing, is to create a Model class under the new data model  projects. For it, add a class file named Student.cs and write the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace MVCDataModel  
  7. {  
  8.     public class Student  
  9.     {  
  10.         public int StudentId { getset; }  
  11.         public string StudentName { getset; }  
  12.         public string FatherName { getset; }  
  13.         public DateTime DateOfBirth { getset; }  
  14.         public string Address { getset; }  
  15.         public string Class { getset; }  
  16.         public int RollNo { getset; }  
  17.     }  
  18. }  
Now create a table named Student in the database as per the above data model objects.
 
Now add another new class under the MVCDataService project named BaseService.cs. This class is used as a base class for the base service of database operations. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.SqlClient;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace MVCDataService  
  10. {  
  11.     public class BaseService  
  12.     {  
  13.         public string DBConnection { getset; }  
  14.   
  15.         public BaseService(string connString)  
  16.         {  
  17.             this.DBConnection = connString;  
  18.         }  
  19.   
  20.         public int InsertUpdateDeleteData(string commandText)  
  21.         {  
  22.             using (SqlConnection conn = new SqlConnection(this.DBConnection))  
  23.             {  
  24.                 conn.Open();  
  25.                 SqlCommand myCommand = new SqlCommand(commandText, conn);  
  26.                 int status = myCommand.ExecuteNonQuery();  
  27.                 conn.Close();  
  28.                 return status;  
  29.             }  
  30.         }  
  31.   
  32.         public DataTable FetchData(string commandText)  
  33.         {  
  34.             using (SqlConnection conn = new SqlConnection(this.DBConnection))  
  35.             {  
  36.                 conn.Open();  
  37.                 SqlCommand myCommand = new SqlCommand(commandText, conn);  
  38.                 SqlDataReader reader =  myCommand.ExecuteReader();  
  39.                 DataTable dtData = new DataTable();  
  40.                 dtData.Load(reader);  
  41.                 conn.Close();  
  42.                 return dtData;  
  43.             }  
  44.         }  
  45.     }  
  46. }  
Now, add another class StudentService.cs in the same project and write down the following code:
  1. using MVCDataModel;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7.   
  8. namespace MVCDataService  
  9. {  
  10.     public class StudentService : BaseService  
  11.     {  
  12.         public StudentService(string conString)  
  13.             : base(conString)  
  14.         {  
  15.   
  16.         }  
  17.   
  18.         public bool InsertStudentData(Student objStudent)  
  19.         {  
  20.             string strUrl = "Insert Into Student(StudentName,FatherName,DOB,Address,Class,RollNo) values (";  
  21.             strUrl += "'" + objStudent.StudentName + "',";  
  22.             strUrl += "'" + objStudent.FatherName + "',";  
  23.             strUrl += "'" + objStudent.DateOfBirth + "',";  
  24.             strUrl += "'" + objStudent.Address + "',";  
  25.             strUrl += "'" + objStudent.Class + "',";  
  26.             strUrl += "" + Convert.ToString(objStudent.RollNo) + ")";  
  27.             int iStatus = base.InsertUpdateDeleteData(strUrl);  
  28.             return true;  
  29.         }  
  30.   
  31.         public List<Student> GetStudentList()  
  32.         {  
  33.             List<Student> lstData = new List<Student>();  
  34.             DataTable dtData = base.FetchData("Select * from Student");  
  35.             lstData = (from dr1 in dtData.AsEnumerable()  
  36.                        select new Student  
  37.                        {  
  38.                            StudentId = dr1.Field<Int32>("StudentId"),  
  39.                            StudentName = dr1.Field<string>("StudentName"),  
  40.                            FatherName = dr1.Field<string>("FatherName"),  
  41.                            Address = dr1.Field<string>("Address"),  
  42.                            Class = dr1.Field<string>("Class"),  
  43.                            RollNo = dr1.Field<Int32>("RollNo"),  
  44.                            DateOfBirth = dr1.Field<DateTime>("DOB")  
  45.                        }).ToList();  
  46.             return lstData;  
  47.         }  
  48.     }  
  49. }  
Now, we need to add database connection details in the web config file within the configuration tag.  
  1. <connectionStrings>  
  2.    <add name="conn" connectionString="Data Source=DEB;Initial Catalog=ProjectSample;Password=abc;Integrated Security=True" providerName="System.Data.SqlClient" />  
  3.  </connectionStrings>  
Now we add a controller file named BaseController.cs  and add the following code:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace MVC_Article.Controllers  
  9. {  
  10.     public class BaseController : Controller  
  11.     {  
  12.         public string ConnectionString { getset; }  
  13.   
  14.         public void setConnectionString()  
  15.         {  
  16.             ConnectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;  
  17.         }  
  18.    
  19.     }  
  20. }  
Now we make the changes in the student controller as in the following:
  1. using MVCDataModel;  
  2. using MVCDataService;  
  3. using System.Collections.Generic;  
  4. using System.Web.Mvc;  
  5.   
  6. namespace MVC_Article.Controllers  
  7. {  
  8.     public class StudentController : BaseController  
  9.     {  
  10.         public StudentController()  
  11.         {  
  12.             base.setConnectionString();  
  13.         }  
  14.   
  15.         // GET: Student  
  16.         public ViewResult Index()  
  17.         {  
  18.             StudentService objStudentService = new StudentService(base.ConnectionString);  
  19.             List<Student> lstData = objStudentService.GetStudentList();  
  20.             return View(lstData);  
  21.         }  
  22.   
  23.         [HttpGet]  
  24.         public ViewResult StudentAdd()  
  25.         {  
  26.             return View();  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         public ViewResult StudentAdd(Student studentData)  
  31.         {  
  32.             StudentService objStudentService = new StudentService(base.ConnectionString);  
  33.             if (objStudentService.InsertStudentData(studentData))  
  34.             {  
  35.                 return View("ConfirmStudent", studentData);  
  36.             }  
  37.             else  
  38.             {  
  39.                 return View(studentData);  
  40.             }  
  41.         }  
  42.     }  
  43. }  
Now we make some changes in the Index.cshtml file as in the following:
  1. @model IEnumerable<MVCDataModel.Student>  
  2. @{  
  3.     ViewBag.Title = "Index";  
  4. }  
  5.   
  6. <html>  
  7. <head>  
  8.     <meta name="viewport" content="width=device-width" />  
  9.     <title> Student Add</title>  
  10.     <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  11.     <script src="~/Scripts/jquery-2.1.4.min.js"></script>  
  12.     <script src="~/Scripts/bootstrap.min.js"></script>  
  13. </head>  
  14. <body>  
  15.     <h2>Student Database Project</h2>  
  16.     <div class="btn-link">  
  17.         @Html.ActionLink("Register Student", "StudentAdd")  
  18.         <hr />  
  19.         <br />  
  20.         <table border="1" style="width:100%;">  
  21.             <thead>  
  22.                 <tr style="background-color:WindowFrame;color:maroon;font-weight:bold;">  
  23.                     <td>Student Name</td>  
  24.                     <td>Father Name</td>  
  25.                     <td>Address</td>  
  26.                     <td>Date of Birth</td>  
  27.                     <td>Course</td>  
  28.                     <td>Roll No</td>  
  29.                     <td></td>  
  30.                     <td></td>  
  31.                 </tr>  
  32.             </thead>  
  33.             <tbody>  
  34.                 @foreach (var data in Model)  
  35.                 {  
  36.                     <tr>  
  37.                         <td>@Html.DisplayFor(modelItem => data.StudentName) </td>  
  38.                         <td>@Html.DisplayFor(modelItem => data.FatherName) </td>  
  39.                         <td>@Html.DisplayFor(modelItem => data.Address) </td>  
  40.                         <td>@Html.DisplayFor(modelItem => data.DateOfBirth) </td>  
  41.                         <td>@Html.DisplayFor(modelItem => data.Class) </td>  
  42.                         <td>@Html.DisplayFor(modelItem => data.RollNo) </td>  
  43.                         <td>@Html.ActionLink("Edit","")</td>  
  44.                         <td>@Html.ActionLink("Delete","")</td>  
  45.                     </tr>  
  46.                 }  
  47.             </tbody>  
  48.         </table>  
  49.     </div>  
  50.   
  51. </body>  
  52. </html>  
Also, we make some changes in the StudentAdd.cshtml file as in the following:
  1. @model MVCDataModel.Student  
  2.   
  3. @{  
  4.     Layout = null;  
  5. }  
  6.   
  7. <!DOCTYPE html>  
  8.   
  9. <html>  
  10. <head>  
  11.     <meta name="viewport" content="width=device-width" />  
  12.     <title> Student Add</title>  
  13.     <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  14.     <script src="~/Scripts/jquery-2.1.4.min.js"></script>  
  15.     <script src="~/Scripts/bootstrap.min.js"></script>  
  16. </head>  
  17. <body>  
  18.     @using (Html.BeginForm())  
  19.     {  
  20.         @Html.AntiForgeryToken()  
  21.   
  22.         <div class="form-horizontal">  
  23.             <h2>Register New Student</h2>  
  24.             <hr />  
  25.             @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  26.             <div class="form-group">  
  27.                 @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = "control-label col-md-2" })  
  28.                 <div class="col-md-10">  
  29.                     @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })  
  30.                     @Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" })  
  31.                 </div>  
  32.             </div>  
  33.   
  34.             <div class="form-group">  
  35.                 @Html.LabelFor(model => model.FatherName, htmlAttributes: new { @class = "control-label col-md-2" })  
  36.                 <div class="col-md-10">  
  37.                     @Html.EditorFor(model => model.FatherName, new { htmlAttributes = new { @class = "form-control" } })  
  38.                     @Html.ValidationMessageFor(model => model.FatherName, "", new { @class = "text-danger" })  
  39.                 </div>  
  40.             </div>  
  41.   
  42.             <div class="form-group">  
  43.                 @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })  
  44.                 <div class="col-md-10">  
  45.                     @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })  
  46.                     @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })  
  47.                 </div>  
  48.             </div>  
  49.   
  50.             <div class="form-group">  
  51.                 @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })  
  52.                 <div class="col-md-10">  
  53.                     @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })  
  54.                     @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })  
  55.                 </div>  
  56.             </div>  
  57.   
  58.             <div class="form-group">  
  59.                 @Html.LabelFor(model => model.Class, htmlAttributes: new { @class = "control-label col-md-2" })  
  60.                 <div class="col-md-10">  
  61.                     @Html.DropDownListFor(x => x.Class, new[] {  
  62.                     new SelectListItem() {Text="BCA",Value="BCA"},  
  63.                     new SelectListItem() {Text="BBA",Value="BBA"},  
  64.                     new SelectListItem() {Text="BTECH",Value="BTECH"},  
  65.                     new SelectListItem() {Text="BCA",Value="MCA"},  
  66.                     new SelectListItem() {Text="BBA",Value="MBA"},  
  67.                     new SelectListItem() {Text="BTECH",Value="MTECH"}  
  68.                })  
  69.                     @Html.ValidationMessageFor(model => model.Class, "", new { @class = "text-danger" })  
  70.                 </div>  
  71.             </div>  
  72.   
  73.             <div class="form-group">  
  74.                 @Html.LabelFor(model => model.RollNo, htmlAttributes: new { @class = "control-label col-md-2" })  
  75.                 <div class="col-md-10">  
  76.                     @Html.EditorFor(model => model.RollNo, new { htmlAttributes = new { @class = "form-control" } })  
  77.                     @Html.ValidationMessageFor(model => model.RollNo, "", new { @class = "text-danger" })  
  78.                 </div>  
  79.             </div>  
  80.   
  81.             <div class="form-group">  
  82.                 <div class="col-md-offset-2 col-md-10">  
  83.                     <input type="submit" value="Create" class="btn btn-success" />  
  84.                 </div>  
  85.             </div>  
  86.         </div>  
  87.     }  
  88.   
  89.     <div>  
  90.         @Html.ActionLink("Back to Home", "Index")  
  91.     </div>  
  92. </body>  
  93.   
  94. </html>  
Now run the projects. Click on Register Student Button and save student details. Then click on Back to Index page and students list will appear as in the following screenshot: 


Similar Articles