0% found this document useful (0 votes)
14 views14 pages

Net Practical

The document outlines the steps to create a CRUD application for managing employee data using Visual Studio and SQL Server. It details the creation of databases and tables, setting up models and controllers in an ASP.NET MVC application, and implementing JavaScript functions for data manipulation. The document includes specific code snippets for various components such as the EmployeeController, EmployeeViewModel, and front-end views.

Uploaded by

Faisal Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views14 pages

Net Practical

The document outlines the steps to create a CRUD application for managing employee data using Visual Studio and SQL Server. It details the creation of databases and tables, setting up models and controllers in an ASP.NET MVC application, and implementing JavaScript functions for data manipulation. The document includes specific code snippets for various components such as the EmployeeController, EmployeeViewModel, and front-end views.

Uploaded by

Faisal Khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

WebAppCRUDOperation Project

FAISAL KHAN
21102012

 Steps to create Employee FORM to apply CRUD


operation in Visual Studio:-
1.) Open SSMS software through the search bar and connect the database.(No
changes while connecting directly just click connect)

2.) Right click on the database --> New database --> Name database as
EmployeeDB --> Click on OK --> From drop down list of database Right
click on table -->New table.

3.) Name the first table as : - Employees

 Fields are as below for above table:


a) EmployeeId - integer(data type) remove allow null set primary key.
b) FirstName- varchar(150) remove allow null don't set primary key.
c) LastName- varchar(150) remove allow null.
d) Department -varchar(150) remove allow null.
e) JobType- varchar(150) remove allow null.
f) Salary-decimal(18,2) remove allow null.
g) CityId-int remove allow null.

 Click on whole table in properties right table name Employees


o And in identity coloum select EmployeeId
o And ctrl +s and refresh the page to check the changes done.

4.) Again CREATE NEW TABLE :- Cities

 Fields should as below:-


o CityId-int remove allow null set primary key.
o Name -varchar(150) remove allow null.

 Open properties name as Cities In identity column select CityId.


o Press Ctrl+s.

5.) Right click on dbo_cities from left side and click on add 200 rows
o And add cities name:
 Pune
 Surat
 Rajkot
 Mumbai
 Vadodara

6.) Same add data in dbo.employees and add 200 rows.


o And add employee details:
 Rajal. Shah. HR. Relationship Manager. 2876399. Pune

 Steps for Visual Studio:-

1.) Open VISUAL STUDIO.

2.) Create new project  Search for “asp.net web application”.

3.) Name WebAppCRUDOperation  Click on create.

4.) Select Empty  right side click on “MVC”  And then create.

5.) Right click on models  click on add  new items Left side select data 
Select ado.net empty data model  Change the name below and write
“EmployeeDbModel” instead of “Model1”  Click on Add  Click on next
 Click on new connection  select Microsoft SQL Server  Click OK 
in Server name copy the server name from ssms connection  in select or
enter database  select EmployeeDBEntites  Click OK  Click on next 
Click on next Select whole table of “table” as shown below  Click on
finish  Click ok on security msg.

Select this table


 click on finish
6.) Now right click controller  click on add  controller  “MVC5 Cotroller-
Empty”  In place of DefaultConteoller write “HomeController”  Add.

7.) Now again right click controller  click on add  controller  “MVC5
Cotroller-Empty”  In place of DefaultConteoller write
“EmployeeController”  Add.

8.) Click right on main project name  click on manage NuGet Packages 
Click ob browser  write microsoft.jquery Download as shown below
and it will take few minutes to download.

9.) In views folder  right click on Employee folder  click on Add  Click
on view  click on MVC5 view  add  and give view name “index”
instead of “view”  Click on Add.

10.) In views folder  right click on Home folder  click on Add  Click on
view  click on MVC5 view  add  and give view name “index” instead
of “view”  Click on Add.

11.) In views folder  In shared folder  Click on “_Layout.cshtml”  copy


the below code which is in orange color:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>

<script src="~/Scripts/jquery-1.8.0.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-
target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new
{ @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">

<li>@Html.ActionLink(linkText: "Home", actionName: "Index",


controllerName: "Home") </li>
<li>@Html.ActionLink(linkText: "Contact", actionName: "Contact",
controllerName: "Home") </li>
<li>@Html.ActionLink(linkText: "About", actionName: "About",
controllerName: "Home") </li>
<li>@Html.ActionLink(linkText: "Employee", actionName: "Index",
controllerName: "Employee") </li>
</ul>
</div>
</div>
</div>

<div class="container body-content">


@RenderBody()
<hr />
<footer>
<p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
</body>
</html>
12.) Now in HomeController.cs code the below code which is in orange color:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebAppCRUDOperation.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}

public ActionResult Contact()


{
return View();
}

public ActionResult About()


{
return View();
}
}
}

13.) Now in scripts folder add 2 js file from students folder. In students folder
 jquery  scripts  2 bootstraps file hain woh copy paste karni hai scripts
folder mein.

14.) Now in content folder add 8 js file from students folder. In students folder
 8 bootstraps file hain woh copy paste karni hai content folder mein.

15.) Now right click on main project name  Click on Add  give name as
“Viewmodel” then enter  right click on Viewmodel folder  add  click
on class  click on class as shown below and give name as
“EmployeeViewModel.cs” instead of “class.cs”.
16.) Now in EmployeeController.cs copy the whole code given below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using System.Web.Services.Description;
using WebAppCRUDOperation.Models;
using WebAppCRUDOperation.Viewmodel;

namespace WebAppCRUDOperation.Controllers
{
public class EmployeeController : Controller
{
private EmployeeDBEntities objEmployeeDbEntities;

public EmployeeController()
{
objEmployeeDbEntities = new EmployeeDBEntities();
}
// GET: Employee
public ActionResult Index()
{
ViewBag.Cities = (from obj in objEmployeeDbEntities.Cities
select new SelectListItem()
{
Text = obj.Name,
Value = obj.CityId.ToString()
}).ToList();
return View();
}
public JsonResult GetAllEmployee()
{

var employeeRecord = (from objEmp in objEmployeeDbEntities.Employees


join
objCities in objEmployeeDbEntities.Cities on
objEmp.CityId equals objCities.CityId
select new
{
EmployeeId = objEmp.EmployeeId,
FirstName = objEmp.FirstName,
LastName = objEmp.LastName,
Department = objEmp.Department,
JobType = objEmp.JobType,
Salary = objEmp.Salary,
CityId = objEmp.CityId,
Name = objCities.Name

).ToList();
return Json(data: new { Success = true, data = employeeRecord },
JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult AddUpdateEmployee(EmployeeViewModel
objEmployeeViewModel)
{
string Message = "Data successfully Update";
if (!ModelState.IsValid)
{
var errorList = (from item in ModelState
where item.Value.Errors.Any()
select item.Value.Errors[0].ErrorMessage).ToList();

return Json(data: new { Success = false, Message = "some problem in validation",


ErrorList = errorList });
}

Employee objEmployee = objEmployeeDbEntities.Employees.


SingleOrDefault(model => model.EmployeeId ==
objEmployeeViewModel.EmployeeId) ?? new Employee();
objEmployee.EmployeeId = objEmployee.EmployeeId;

objEmployee.FirstName = objEmployeeViewModel.FirstName;
objEmployee.LastName = objEmployeeViewModel.LastName;
objEmployee.Department = objEmployeeViewModel.Department;
objEmployee.JobType = objEmployeeViewModel.JobType;
objEmployee.Salary = objEmployeeViewModel.Salary;
objEmployee.CityId = objEmployeeViewModel.CityId;
if (objEmployeeViewModel.EmployeeId == 0)
{
Message = "Data successfully Added";
objEmployeeDbEntities.Employees.Add(objEmployee);
}
objEmployeeDbEntities.SaveChanges();
return Json(data: new { Success = true, Message = Message },
JsonRequestBehavior.AllowGet);

}
public JsonResult EditEmployee(int employeeId)
{
return Json(data: objEmployeeDbEntities.Employees.SingleOrDefault(model =>
model.EmployeeId == employeeId),
JsonRequestBehavior.AllowGet);
}

[HttpPost]
public JsonResult DeleteEmployee(int employeeId)
{
Employee objEmployee =
objEmployeeDbEntities.Employees.Single(model => model.EmployeeId ==
employeeId);
objEmployeeDbEntities.Employees.Remove(objEmployee);
objEmployeeDbEntities.SaveChanges();
return Json(data: new { Success = true, Message = "Data sucessfully deleted" },
JsonRequestBehavior.AllowGet);
}

}
}

17.) Now in EmployeeViewModel.cs copy the whole code given below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace WebAppCRUDOperation.Viewmodel
{
public class EmployeeViewModel
{
public int EmployeeId { get; set; }

[Display(Name = "First Name :")]


[Required(ErrorMessage = "First Name is required")]
public string FirstName { get; set; }
public string LastName { get; set; }

[Display(Name = "Department :")]


[Required(ErrorMessage = "Department is required")]
public string Department { get; set; }

[Display(Name = "job type :")]


[Required(ErrorMessage = "job type is required")]
public string JobType { get; set; }

[Display(Name = "salary :")]


[Required(ErrorMessage = "salary is required")]
public decimal Salary { get; set; }
public int CityId { get; set; }

}
}

18.) Now in View folder  Employee folder  index.cshtml file copy the
whole code given below:
@{
ViewBag.Title = "Index";
}

<script src="~/Scripts/jquery-2.0.0.min.js">

</script>

<script type="text/javascript">
$(document).ready(function () {
LoadEmployee();

});

function EditEmployee(employeeId) {
$.ajax({
async: true,
type: 'GET',
url: '/Employee/EditEmployee',
data: { employeeId: employeeId },
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#txtFirstName").val(data.FirstName);
$("#txtLastName").val(data.LastName);
$("#txtDepartment").val(data.Department);
$("#txtJobType").val(data.JobType);
$("#txtSalary").val(data.Salary);
$("#Cities").val(data.CityId);
$("#txtEmployeeId").val(employeeId);
$("btnSaveUpdate").val('Update Employee');
},
error: function (data) {
alert('There is some problem with edit operation ');
}
});
}
function DeleteEmployee(employeeId) {
var employeeId = { employeeId: employeeId };
confirm('Are you sure you want to delete the employee');
$.ajax({
async: true,
type: 'POST',
url: '/Employee/DeleteEmployee',
data: JSON.stringify(employeeId),
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.Success) {
alert(data.Message);
LoadEmployee();
} else {
alert(data.Message);
}

},
error: function () {
alert('Are you sure you want to delete the employee');
}
})

}
function ResetEmployee() {
$("#txtDepartment").val("");
$("txtEmployeeId").val("0");
$("txtFirstName").val("");
$("txtJobType").val("");
$("txtLastName").val("");
$("txtSalary").val("");
$('#ErrorMessage').empty();
$("#btnSaveUpdate").val("Add Employee");
$("#Cities").val("1");
}
function AddEmployee() {

var EmployeeViewModel = {
EmployeeId: $("#txtEmployeeId").val(),
FirstName: $("#txtFirstName").val(),
LastName: $("#txtLastName").val(),
Department: $("#txtDepartment").val(),
JobType: $("#txtJobType").val(),
Salary: $("#txtSalary").val(),
CityId: $("#Cities").val(),

}
var errorMessage = "";
$.ajax({
async: true,
type: 'POST',
url: '/Employee/AddUpdateEmployee',
data: JSON.stringify(EmployeeViewModel),
dataType: 'JSON',
contentType: 'application/json;charset=uft=8',
success: function (data) {
if (data.Success) {
alert(data.Message);
LoadEmployee();
ResetEmployee();

} else {
$.each(data.ErrorList, function (index, value) {
errorMessage += value + '<br/>';

});
$('#ErrorMessage').empty();
$('#ErrorMessage').append(errorMessage);
}

},
error: function () {
alert('There is some problem to add update employee.');
}

})
}
function LoadEmployee() {
var BindEmployee = "";
$.ajax({
async: true,
type: 'GET',
url: '/Employee/GetAllEmployee',
datatype: 'JSON',
contentType: 'application/json;charset=uf-8',
success: function (resposnse) {
if (resposnse.Success) {
$.each(resposnse.data,
function (index, value) {
BindEmployee += '<tr><td>' +
value.FirstName +
'</td><td>' +
value.LastName +
'</td><td>' +
value.Department +
'</td><td>' +
value.JobType +
'</td><td>' +
value.Salary +
'</td><td>' +
value.Name +
'</td><td>' +
'<input type="button" value="Edit" name="Edit"
onclick="EditEmployee(' + value.EmployeeId + ')"> || <input type="button" value="Delete"
name="Delete" onclick="DeleteEmployee(' + value.EmployeeId + ')">' +
'</td></tr>';
});

$("#tableEmployee").find('tr:gt(0)').remove();
$("#tableEmployee").append(BindEmployee);

}
},
error: function () {
alert('There is problem to load employee')
}

});
}
</script>

<br />
<br />

<input type="hidden" value="0" id="txtEmployeeId" />

<table style="width : 100%" class="table-bordered" id="tableEmployee">


<thead>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Department
</th>
<th>
Job type
</th>
<th>
Salary
</th>
<th>
City
</th>
<th>
Action
</th>
</tr>
</thead>

</table>

<br />
<br />

<input type="hidden" value="0" id="txtEmployeeId" />


<br />
<div class="text-danger" id="ErrorMessage">

</div>
<br />
<table>
<tr>
<td>
First Name :
</td>
<td>
<input type="text" name="FirstName" id="txtFirstName" />
</td>
</tr>
<tr>
<td>
Last Name :
</td>
<td>
<input type="text" name="LastName" id="txtLastName" />
</td>
</tr>
<tr>
<td>
Department :
</td>
<td>
<input type="text" name="Department" id="txtDepartment" />
</td>
</tr>
<tr>
<td>
Job Type :
</td>
<td>
<input type="text" name="JobType" id="txtJobType" />
</td>
</tr>
<tr>
<td>
Salary :
</td>
<td>
<input type="text" name="Salary" id="txtSalary" />
</td>
</tr>

<tr>
<td>City :</td>
<td>@Html.DropDownList("Cities", (IEnumerable<SelectListItem>)ViewBag.Cities,
"All Cities", new { @class = "form-control search-slt" })</td>
</tr>
<tr>
<td>
</td>
<td>
<table>
<tr>
<td>
<input id="btnSaveUpdate" type="button" value="Add Employee"
onclick="AddEmployee()" />
</td>
<td>
<input type="button" value="Reset Employee" onclick="ResetEmployee()" />
</td>
</tr>
</table>
</td>
</tr>
</table>

19.) Now run the index,cshtml file which is in : View folder  Employee
foler  index.cshtml file.

20.) After run the file just try to add, edit and delete it.

END OF PROJECT

You might also like