sameer gaikwad blog #mesameergaikwad
Introduction
In this article, I am going to explain how to create an MVC web application in ASP.NET Core 2.0 using ADO.NET. We will be creating a sample Employee Record Management System and performing CRUD operations on it.
We will be using Visual Studio 2017 (Version 15.3.5 or above) and SQL Server.
Prerequisites
- Install .NET Core 2.0.0 or above SDK
- Install Visual Studio 2017 Community Edition (Version 15.3.5 or above)
Now, we are ready to proceed with the creation of our MVC web application.
Source Code
Before proceeding further i would recommend to download the source code from Github.
Creating Table and Stored Procedures
We will be using a DB table to store all the records of employees.
Open SQL Server and use the following script to create tblEmployee table.
Now, we will create stored procedures to add, delete, update, and get employee data.
To insert an Employee Record
To update an Employee Record
For deleting an Employee Record
Fetch all Employee Records
Now, our Database part has been completed. So, we will proceed to create the MVC application using Visual Studio.
Create MVC Web Application
Open Visual Studio and select File >> New >> Project.
After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel.
Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as MVCDemoApp and press OK. Refer to this image.
After clicking on OK, a new dialog will open asking to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Web application(Model-View-Controller)” template and press OK.
Now our project will open. You can observe that we have Models, Views and Controllers folders already created. We will be adding our files to these folders only.
Adding the Controller to the Application
Right click on Controllers folder and select Add >> New Item
An “Add New Item” dialog box will open. Select Web from the left panel, then select “MVC Controller Class” from templates panel, and put the name as EmployeeController.cs. Press OK.
Now our EmployeeController has been created. We will put all our business logic in this controller.
Adding the Model to the Application
Right click on Models folder and select Add >> Class. Name your class Employee.cs. This class will contain our Employee model properties.
Add one more class file to Models folder. Name it as EmployeeDataAccessLayer.cs . This class will contain our Database related operations.
Now, the Models folder has the following structure.
Open Employee.cs and put the following code in it. Since we are adding the required validators to the fields of Employee class, so we need to use System.ComponentModel.DataAnnotations at the top.
Open EmployeeDataAccessLayer.cs and put the following code to handle database operations. Make sure to put your connection string.
Now, we will proceed to create our Views.
Adding Views to the Application
To add views for our controller class, we need to create a folder inside Views folder with the same name as our controller and then add our views to that folder.
Right-click on the Views folder, and then Add >> New Folder and name the folder as Employee.
Now Right click on the Views/Employee folder, and then select Add >> New Item.
An “Add New Item” dialog box will open. Select Web from the left panel, then select “MVC View Page” from templates panel, and put the name as Index.cshtml. Press OK.
Thus we have created our first view. Similarly add 4 more views in Views/Employee folder, Create.cshtml, Delete.cshtml, Details.cshtml, and Edit.cshtml.
Now, our Views folder will look like this
Since our Views has been created, we will put codes in View and Controller for performing CRUD operations.
Create View
This view will be used to Add new employee data to the database.
Open Create.cshtml and put following code into it.
To handle database operations, we will create an object of EmployeeDataAccessLayer class inside the EmployeeController class.
To handle the business logic of create, open EmployeeController.cs and put following code into it.
The [Bind] attribute is used with parameter “employee” to protect against over-posting.To know more about over-posting visit here
Index View
This view will be displaying all the employee records present in the database. Additionally, we will also be providing action methods Edit, Details and Delete on each record.
Open Index.cshtml and put following code in it
To handle the business logic of Index view, open EmployeeController.cs and add following code in Index method.
Edit View
This view will enable us to edit an existing employee data.
Open Edit.cshtml and put following code into it.
To handle the business logic of Edit view, open EmployeeController.cs and add following code to it.
As you can observe that we have two Edit action methods, one for HttpGet and another for HttpPost.The HttpGet Edit action method will fetch the employee data and populates the fields of edit view. Once the user clicks on Save button after editing the record, a Post request will be generated which is handled by HttpPost Edit action method.
Details View
This view will display the details of a particular employee.
Open Details.cshtml and put following code into it.
To handle the business logic of Details view,open EmployeeController.cs and add following code to it.
Delete View
This view will help us to remove employee data .
Open Delete.cshtml and put following code into it.
To handle the business logic of Delete view, open EmployeeController.cs and add following code to it.
To complete Delete operation we need two Delete methods accepting same parameter (Employee Id). But two methods with same name and method signature will create a compile time error and if we rename the Delete method then routing won’t be able to find it as asp.net maps URL segments to action methods by name. So, to resolve this issue we put ActionName(“Delete”) attribute to the DeleteConfirmed method. That attribute performs mapping for the routing system so that a URL that includes /Delete/ for a POST request will find the DeleteConfirmed method.
When we click on Delete link on the Index page, it will send a Get request and return a View of the employee using HttpGet Delete method. When we click on Delete button on this view, it will send a Post request to delete the record which is handled by the HttpPost DeleteConfirmed method. Performing a delete operation in response to a Get request (or for that matter, performing an edit operation, create operation, or any other operation that changes data) opens up a security hole. Hence, we have two separate methods.
And that’s it. We have created our first ASP.NET Core MVC web application. Before launching the application, we will configure route URLs. Open Startup.cs file to set the format for routing.Scroll down to app.UseMvc method, where you can set the route url.Make sure that your route url is set like this
This url pattern sets HomeController as default controller and Index method as default action method, whereas Id parameter is optional. Default and optional route parameters need not be present in the URL path for a match. If we do not append any controller name in the URL then it will take HomeController as default controller and Index method of HomeController as default action method. Similarly, if we append only Controller name in the URL, it will navigate to Index action method of that controller.
Execution Demo
Now press F5 to launch the application and navigate to Employee controller by appending /Employeein the URL.
You can see the page as shown below.
Click on CreateNew to navigate to Create view. Add a new Employee record as shown in the image below.
If we miss the data in any field while creating employee record, we will get a required field validation error message.
After inserting the data in all the fields, click on “Create” button. The new employee record will be created and you will be redirected to the Index view, displaying records of all the employees. Here, we can also see action methods Edit, Details, and Delete.
If we want to edit an existing employee record, then click Edit action link. It will open Edit View as below where we can change the employee data.
Here we have changed the Department of employee Swati from Finance to HR.Click on “Save” to return to the Index view to see the updated changes as highlighted in the image below.
If we miss any fields while editing employee records, then Edit view will also throw required field validation error message
If you want to see the details of any Employee, then click on Details action link, which will open the Details view, as shown in the image below.
Click on “Back to List” to go back to Index view. Now, we will perform Delete operation on an employee named Venkat. Click on Delete action link which will open Delete view asking for a confirmation to delete.
Once we click on Delete button, it will send HttpPost request to delete employee record and we will be redirected to the Index view. Here, we can see that the employee with name Venkat has been removed from our record.
Step 1 : Create an MVC Application.
Now let us start with a stepbystep approach from the creation of simple MVC application as in the following:
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "File", then "New" and click "Project..." then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK. After clicking, the following window will appear:
- As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application whose Solution Explorer will look like the following:
Note: It is not mandatory that Model class should be in Model folder, it is just for better readability you can create this class anywhere in the solution explorer. This can be done by creating different folder name or without folder name or in a separate class library.
EmpModel.cs class code snippet:
- public class EmpModel
- {
- [Display(Name = "Id")]
- public int Empid { get; set; }
- [Required(ErrorMessage = "First name is required.")]
- public string Name { get; set; }
- [Required(ErrorMessage = "City is required.")]
- public string City { get; set; }
- [Required(ErrorMessage = "Address is required.")]
- public string Address { get; set; }
- }
Step 3: Create Controller.
Now let us add the MVC 5 controller as in the following screenshot:
Note: The controller name must be having suffix as 'Controller' after specifying the name of controller.
Step 4 : Create Table and Stored procedures.
Now before creating the views let us create the table name Employee in database according to our model fields to store the details:
I hope you have created the same table structure as shown above. Now create the stored procedures to insert, update, view and delete the details as in the following code snippet:
To Insert Records
- Create procedure [dbo].[AddNewEmpDetails]
- (
- @Name varchar (50),
- @City varchar (50),
- @Address varchar (50)
- )
- as
- begin
- Insert into Employee values(@Name,@City,@Address)
- End
- Create Procedure [dbo].[GetEmployees]
- as
- begin
- select *from Employee
- End
- Create procedure [dbo].[UpdateEmpDetails]
- (
- @EmpId int,
- @Name varchar (50),
- @City varchar (50),
- @Address varchar (50)
- )
- as
- begin
- Update Employee
- set Name=@Name,
- City=@City,
- Address=@Address
- where Id=@EmpId
- End
- Create procedure [dbo].[DeleteEmpById]
- (
- @EmpId int
- )
- as
- begin
- Delete from Employee where Id=@EmpId
- End
Now create Repository folder and Add EmpRepository.cs class for database related operations, after adding the solution explorer will look like the following screenshot:
Now create methods in EmpRepository.cs to handle the CRUD operation as in the following screenshot:
EmpRepository.cs
- public class EmpRepository
- {
- private SqlConnection con;
- //To Handle connection related activities
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();
- con = new SqlConnection(constr);
- }
- //To Add Employee details
- public bool AddEmployee(EmpModel obj)
- {
- connection();
- SqlCommand com = new SqlCommand("AddNewEmpDetails", con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue("@Name", obj.Name);
- com.Parameters.AddWithValue("@City", obj.City);
- com.Parameters.AddWithValue("@Address", obj.Address);
- con.Open();
- int i = com.ExecuteNonQuery();
- con.Close();
- if (i >= 1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- //To view employee details with generic list
- public List<EmpModel> GetAllEmployees()
- {
- connection();
- List<EmpModel> EmpList =new List<EmpModel>();
- SqlCommand com = new SqlCommand("GetEmployees", con);
- com.CommandType = CommandType.StoredProcedure;
- SqlDataAdapter da = new SqlDataAdapter(com);
- DataTable dt = new DataTable();
- con.Open();
- da.Fill(dt);
- con.Close();
- //Bind EmpModel generic list using dataRow
- foreach (DataRow dr in dt.Rows)
- {
- EmpList.Add(
- new EmpModel {
- Empid = Convert.ToInt32(dr["Id"]),
- Name =Convert.ToString( dr["Name"]),
- City = Convert.ToString( dr["City"]),
- Address = Convert.ToString(dr["Address"])
- }
- );
- }
- return EmpList;
- }
- //To Update Employee details
- public bool UpdateEmployee(EmpModel obj)
- {
- connection();
- SqlCommand com = new SqlCommand("UpdateEmpDetails", con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue("@EmpId", obj.Empid);
- com.Parameters.AddWithValue("@Name", obj.Name);
- com.Parameters.AddWithValue("@City", obj.City);
- com.Parameters.AddWithValue("@Address", obj.Address);
- con.Open();
- int i = com.ExecuteNonQuery();
- con.Close();
- if (i >= 1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- //To delete Employee details
- public bool DeleteEmployee(int Id)
- {
- connection();
- SqlCommand com = new SqlCommand("DeleteEmpById", con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue("@EmpId", Id);
- con.Open();
- int i = com.ExecuteNonQuery();
- con.Close();
- if (i >= 1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
Now open the EmployeeController.cs and create the following action methods:
- public class EmployeeController : Controller
- {
- // GET: Employee/GetAllEmpDetails
- public ActionResult GetAllEmpDetails()
- {
- EmpRepository EmpRepo = new EmpRepository();
- ModelState.Clear();
- return View(EmpRepo.GetAllEmployees());
- }
- // GET: Employee/AddEmployee
- public ActionResult AddEmployee()
- {
- return View();
- }
- // POST: Employee/AddEmployee
- [HttpPost]
- public ActionResult AddEmployee(EmpModel Emp)
- {
- try
- {
- if (ModelState.IsValid)
- {
- EmpRepository EmpRepo = new EmpRepository();
- if (EmpRepo.AddEmployee(Emp))
- {
- ViewBag.Message = "Employee details added successfully";
- }
- }
- return View();
- }
- catch
- {
- return View();
- }
- }
- // GET: Employee/EditEmpDetails/5
- public ActionResult EditEmpDetails(int id)
- {
- EmpRepository EmpRepo = new EmpRepository();
- return View(EmpRepo.GetAllEmployees().Find(Emp => Emp.Empid == id));
- }
- // POST: Employee/EditEmpDetails/5
- [HttpPost]
- public ActionResult EditEmpDetails(int id,EmpModel obj)
- {
- try
- {
- EmpRepository EmpRepo = new EmpRepository();
- EmpRepo.UpdateEmployee(obj);
- return RedirectToAction("GetAllEmpDetails");
- }
- catch
- {
- return View();
- }
- }
- // GET: Employee/DeleteEmp/5
- public ActionResult DeleteEmp(int id)
- {
- try
- {
- EmpRepository EmpRepo = new EmpRepository();
- if (EmpRepo.DeleteEmployee(id))
- {
- ViewBag.AlertMsg = "Employee details deleted successfully";
- }
- return RedirectToAction("GetAllEmpDetails");
- }
- catch
- {
- return View();
- }
- }
- }
Create the Partial view to Add the employees
To create the Partial View to add Employees, right click on ActionResult method and then click Add view. Now specify the view name, template name and model class in EmpModel.cs and click on Add button as in the following screenshot:
After clicking on Add button it generates the strongly typed view whose code is given below:
AddEmployee.cshtml
- @model CRUDUsingMVC.Models.EmpModel
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-horizontal">
- <h4>Add Employee</h4>
- <div>
- @Html.ActionLink("Back to Employee List", "GetAllEmpDetails")
- </div>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Save" class="btn btn-default" />
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10" style="color:green">
- @ViewBag.Message
- </div>
- </div>
- </div>
- }
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
To view the employee details let us create the partial view named GetAllEmpDetails:
Now click on add button, it will create GetAllEmpDetails.cshtml strongly typed view whose code is given below:
GetAllEmpDetails.CsHtml
- @model IEnumerable<CRUDUsingMVC.Models.EmpModel>
- <p>
- @Html.ActionLink("Add New Employee", "AddEmployee")
- </p>
- <table class="table">
- <tr>
- <th>
- @Html.DisplayNameFor(model => model.Name)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.City)
- </th>
- <th>
- @Html.DisplayNameFor(model => model.Address)
- </th>
- <th></th>
- </tr>
- @foreach (var item in Model)
- {
- @Html.HiddenFor(model => item.Empid)
- <tr>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.City)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Address)
- </td>
- <td>
- @Html.ActionLink("Edit", "EditEmpDetails", new { id = item.Empid }) |
- @Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid }, new { onclick = "return confirm('Are sure wants to delete?');" })
- </td>
- </tr>
- }
- </table>
Follow the same procedure and create EditEmpDetails view to edit the employees. After creating the view the code will be like the following:
EditEmpDetails.cshtml
- @model CRUDUsingMVC.Models.EmpModel
- @using (Html.BeginForm())
- {
- @Html.AntiForgeryToken()
- <div class="form-horizontal">
- <h4>Update Employee Details</h4>
- <hr />
- <div>
- @Html.ActionLink("Back to Details", "GetAllEmployees")
- </div>
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- @Html.HiddenFor(model => model.Empid)
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Update" class="btn btn-default" />
- </div>
- </div>
- </div>
- }
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
The above ActionLink I have added in GetAllEmpDetails.CsHtml view because from there we will delete and update the records.
- public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Employee", action = "AddEmployee", id = UrlParameter.Optional }
- );
- }
- }
Now after adding the all model, views and controller our solution explorer will be look like as in the following screenshot:
From the preceding examples we have learned how to implement CRUD operations in ASP.NET MVC using ADO.NET.
Note:
- Configure the database connection in the web.config file depending on your database server location.
- Download the Zip file of the sample application for a better understanding.
- Since this is a demo, it might not be using proper standards, so improve it depending on your skills
- This application is created completely focusing on beginners.
- Visual Studio 2015
- SQL Server 2008
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- SET ANSI_PADDING ON
- GO
- CREATE TABLE[dbo]. [tblStudent](
- [student_id][int] IDENTITY(1, 1) NOT NULL,
- [student_name][varchar](50) NOT NULL,
- [stduent_age][int] NOT NULL,
- [student_gender][varchar](6) NOT NULL,
- CONSTRAINT[PK_tblStudent] PRIMARY KEY CLUSTERED(
- [student_id] ASC
- ) WITH(PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON[PRIMARY]
- ) ON[PRIMARY]
- GO
- SET ANSI_PADDING OFF
- GO
- Right-click on the “Model” folder. In the context menu select “Add” then choose “New item..”.
- In the popup, select “Code” then choose “Class” and name the class file as “CRUDModel” then click “Add”. That’s all!
- Right-click on the “CRUD” folder under the “Views” folder in the context menu select “Add” then choose “View..”.
- In the popup, give “View name” and uncheck the “Use a layout page” checkbox. Finally, click the “Add” button.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace MVCWithADO {
- public class RouteConfig {
- public static void RegisterRoutes(RouteCollection routes) {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "CRUD", action = "Index", id = UrlParameter.Optional }
- );
- }
- }
- }
View | Purpose |
Home.cshtml | This is the default view. Loaded when the application launched. Will display all the records in the table |
Create.cshtml | Displays control’s to insert the record. Will be rendered when the “Add New Record” button clicked on the “Home.cshtml” view. |
Edit.cshtml | Displays control’s to edit the record. Will be rendered when the “Edit” button clicked on the “Home.cshtml” view. |
- using System.Data;
- using System.Data.SqlClient;
- namespace MVCWithADO.Models {
- public class CRUDModel {
- /// <summary>
- /// Get all records from the DB
- /// </summary>
- /// <returns>Datatable</returns>
- public DataTable GetAllStudents() {
- DataTable dt = new DataTable();
- string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";
- using(SqlConnection con = new SqlConnection(strConString)) {
- con.Open();
- SqlCommand cmd = new SqlCommand("Select * from tblStudent", con);
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- da.Fill(dt);
- }
- return dt;
- }
- /// <summary>
- /// Get student detail by Student id
- /// </summary>
- /// <param name="intStudentID"></param>
- /// <returns></returns>
- public DataTable GetStudentByID(int intStudentID) {
- DataTable dt = new DataTable();
- string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";
- using(SqlConnection con = new SqlConnection(strConString)) {
- con.Open();
- SqlCommand cmd = new SqlCommand("Select * from tblStudent where student_id=" + intStudentID, con);
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- da.Fill(dt);
- }
- return dt;
- }
- /// <summary>
- /// Update the student details
- /// </summary>
- /// <param name="intStudentID"></param>
- /// <param name="strStudentName"></param>
- /// <param name="strGender"></param>
- /// <param name="intAge"></param>
- /// <returns></returns>
- public int UpdateStudent(int intStudentID, string strStudentName, string strGender, int intAge) {
- string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";
- using(SqlConnection con = new SqlConnection(strConString)) {
- con.Open();
- string query = "Update tblStudent SET student_name=@studname, student_age=@studage , student_gender=@gender where student_id=@studid";
- SqlCommand cmd = new SqlCommand(query, con);
- cmd.Parameters.AddWithValue("@studname", strStudentName);
- cmd.Parameters.AddWithValue("@studage", intAge);
- cmd.Parameters.AddWithValue("@gender", strGender);
- cmd.Parameters.AddWithValue("@studid", intStudentID);
- return cmd.ExecuteNonQuery();
- }
- }
- /// <summary>
- /// Insert Student record into DB
- /// </summary>
- /// <param name="strStudentName"></param>
- /// <param name="strGender"></param>
- /// <param name="intAge"></param>
- /// <returns></returns>
- public int InsertStudent(string strStudentName, string strGender, int intAge) {
- string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";
- using(SqlConnection con = new SqlConnection(strConString)) {
- con.Open();
- string query = "Insert into tblStudent (student_name, student_age,student_gender) values(@studname, @studage , @gender)";
- SqlCommand cmd = new SqlCommand(query, con);
- cmd.Parameters.AddWithValue("@studname", strStudentName);
- cmd.Parameters.AddWithValue("@studage", intAge);
- cmd.Parameters.AddWithValue("@gender", strGender);
- return cmd.ExecuteNonQuery();
- }
- }
- /// <summary>
- /// Delete student based on ID
- /// </summary>
- /// <param name="intStudentID"></param>
- /// <returns></returns>
- public int DeleteStudent(int intStudentID) {
- string strConString = @ "Data Source=WELCOME-PC\SQLSERVER2008;Initial Catalog=MyDB;Integrated Security=True";
- using(SqlConnection con = new SqlConnection(strConString)) {
- con.Open();
- string query = "Delete from tblStudent where student_id=@studid";
- SqlCommand cmd = new SqlCommand(query, con);
- cmd.Parameters.AddWithValue("@studid", intStudentID);
- return cmd.ExecuteNonQuery();
- }
- }
- }
- }
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using System.Data;
- using System.Data.SqlClient;
- using MVCWithADO.Models;
- namespace MVCWithADO.Controllers {
- public class CRUDController: Controller {
- /// <summary>
- /// First Action method called when page loads
- /// Fetch all the rows from DB and display it
- /// </summary>
- /// <returns>Home View</returns>
- public ActionResult Index() {
- CRUDModel model = new CRUDModel();
- DataTable dt = model.GetAllStudents();
- return View("Home", dt);
- }
- /// <summary>
- /// Action method, called when the "Add New Record" link clicked
- /// </summary>
- /// <returns>Create View</returns>
- public ActionResult Insert() {
- return View("Create");
- }
- /// <summary>
- /// Action method, called when the user hit "Submit" button
- /// </summary>
- /// <param name="frm">Form Collection Object</param>
- /// <param name="action">Used to differentiate between "submit" and "cancel"</param>
- /// <returns></returns>
- public ActionResult InsertRecord(FormCollection frm, string action) {
- if (action == "Submit") {
- CRUDModel model = new CRUDModel();
- string name = frm["txtName"];
- int age = Convert.ToInt32(frm["txtAge"]);
- string gender = frm["gender"];
- int status = model.InsertStudent(name, gender, age);
- return RedirectToAction("Index");
- } else {
- return RedirectToAction("Index");
- }
- }
- /// <summary>
- /// Action method called when the user click "Edit" Link
- /// </summary>
- /// <param name="StudentID">Student ID</param>
- /// <returns>Edit View</returns>
- public ActionResult Edit(int StudentID) {
- CRUDModel model = new CRUDModel();
- DataTable dt = model.GetStudentByID(StudentID);
- return View("Edit", dt);
- }
- /// <summary>
- /// Actin method, called when users update the record or cancel the update.
- /// </summary>
- /// <param name="frm">Form Collection</param>
- /// <param name="action">Denotes the action</param>
- /// <returns>Home view</returns>
- public ActionResult UpdateRecord(FormCollection frm, string action) {
- if (action == "Submit") {
- CRUDModel model = new CRUDModel();
- string name = frm["txtName"];
- int age = Convert.ToInt32(frm["txtAge"]);
- string gender = frm["gender"];
- int id = Convert.ToInt32(frm["hdnID"]);
- int status = model.UpdateStudent(id, name, gender, age);
- return RedirectToAction("Index");
- } else {
- return RedirectToAction("Index");
- }
- }
- /// <summary>
- /// Action method called when the "Delete" link clicked
- /// </summary>
- /// <param name="StudentID">Stutend ID to edit</param>
- /// <returns>Home view</returns>
- public ActionResult Delete(int StudentID) {
- CRUDModel model = new CRUDModel();
- model.DeleteStudent(StudentID);
- return RedirectToAction("Index");
- }
- }
- }
- @using System.Data
- @using System.Data.SqlClient
- @model System.Data.DataTable
- @{
- Layout = null;
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Home</title>
- </head>
- <body>
- <form method="post" name="Display">
- <h2>Home</h2>
- @Html.ActionLink("Add New Record", "Insert")
- <br />
- @{
- if (Model.Rows.Count > 0)
- {
- <table border="1">
- <thead>
- <tr>
- <td>
- Student ID
- </td>
- <td>
- Name
- </td>
- <td>
- Age
- </td>
- <td>Gender</td>
- </tr>
- </thead>
- @foreach (DataRow dr in Model.Rows)
- {
- <tr>
- <td>@dr["student_id"].ToString() </td>
- <td>@dr["student_name"].ToString() </td>
- <td>@dr["student_age"].ToString() </td>
- <td>@dr["student_gender"].ToString() </td>
- <td>@Html.ActionLink("Edit ", "Edit", new { StudentID = dr["student_id"].ToString() })</td>
- <td>@Html.ActionLink("| Delete", "Delete", new { StudentID = dr["student_id"].ToString() })</td>
- </tr>
- }
- </table>
- <br />
- }
- else
- {
- <span> No records found!!</span>
- }
- }
- </form>
- </body>
- </html>
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Insert</title>
- </head>
- <body>
- <form id="frmDetail" method="post" action="@Url.Action(" InsertRecord")">
- Enter Name:<input name="txtName" />
- <br />
- Enter Age:<input name="txtAge" />
- <br />
- Select Gender: <input type="radio" name="gender" value="male" checked>Male
- <input type="radio" name="gender" value="female">Female
- <br />
- <input type="submit" value="Submit" name="action" />
- <input type="submit" value="Cancel" name="action" />
- </form>
- </body>
- </html>
- @using System.Data
- @using System.Data.SqlClient
- @model System.Data.DataTable
- @{
- ViewBag.Title = "EditView";
- }
- <html>
- <head>
- <script type="text/javascript">
- </script>
- </head>
- <body>
- <form id="frmDetail" method="post" action="@Url.Action(" UpdateRecord")">
- Enter Name:<input name="txtName" value="@Model.Rows[0][" student_name"]" />
- <br />
- Enter Age:<input name="txtAge" value="@Model.Rows[0][" student_age"]" />
- <br />
- Select Gender:
- @if (Model.Rows[0]["student_gender"].ToString().ToLower() == "male")
- {
- <input type="radio" name="gender" value="male" checked /> @Html.Raw("Male")
- <input type="radio" name="gender" value="female" /> @Html.Raw("Female")
- }
- else
- {
- <input type="radio" name="gender" value="male"> @Html.Raw("Male")
- <input type="radio" name="gender" value="female" checked /> @Html.Raw("Female")
- }
- <input type="hidden" name="hdnID" value="@Model.Rows[0][" student_id"]" />
- <br />
- <input type="submit" value="Submit" name="action" />
- <input type="submit" value="Cancel" name="action" />
- </form>
- </body>
- </html>
0 Comments