It Is Intimated That Following Lectures Will Not Be Repeated and Would Be Part of Mid-Term& Final Exam As Well

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Web Engineering (CS-666/CS-723)

Mr. Aftab Khan Email id: aftab@biit.edu.pk WhatsApp# 0344-8184704


Mr. Amir Rashid Email id: amir@biit.edu.pk, WhatsApp# 0302-5698539

Note:
It is intimated that following Lectures will not be repeated and would be part
of mid-term& final exam as well.

(Week 8) Lecture 15-16 Objectives:


Learning objectives of this lecture are

• Show details of individual record in MVC application


• Edit/update the record in MVC Application
• Delete the record from Database
Text Book & Resources: Professional ASP.NET MVC 5 by Jon Galloway, Brad Wilson, K. Scott Allen, David
Matson

Video Links:
https://www.youtube.com/watch?v=WxUF3u_N5Eo&list=PLjVp2I_4DPy_4CvU-
mdB_vfHfT8k7o18N&index=15&t=8s

https://www.youtube.com/watch?v=RjdBm8Vmi7A&list=PLjVp2I_4DPy_4CvU-
mdB_vfHfT8k7o18N&index=16&t=330s

https://www.youtube.com/watch?v=TBDrQdAD_XY&list=PLjVp2I_4DPy_4CvU-
mdB_vfHfT8k7o18N&index=17&t=676s

Showing Details of individual row in new view

In the previous lecture we have discussed how to fetch employee data from database and
show the records on view of MVC application. But that was view only table. We have no
option to view details of each record or edit and delete the given record. In this lecture we
will learn how to add details / edit and delete options to perform these common tasks. We
will add Index view using visual studio wizard. You can safely remove the index view
created in previous lecture.
Right click on index Action in the employee controller and select add view as depicted
in the Figure 1.Now the wizard that displayed up has the name of the view according to
action name and auto-filled by Visual Studio. Awesome! It will also generate any required
View subfolders and place the file in the accurate one.

You have to select model class (Employee class in our case) and select list from template
dropdown as shown Figure 2.

It will create index view in the Employee subfolder and code to create edit, detail and delete
button will be already added in the end of view along with all necessary code to view
employee records in table format.

Figure 1
Figure 2

Here is the generated code of index view.


@model IEnumerable<MVCDemo.Models.Employee>

@{
Layout = null;
}

<!DOCTYPE html>

<html> <head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head> <body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.Gender)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.EmailAddress)
</th>
<th>
@Html.DisplayNameFor(model => model.Salary)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.EducationLevel)
</th>
<th>
@Html.DisplayNameFor(model => model.HireDate)
</th>
<th></th>
</tr>

@foreach (var item in Model) {


<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.EducationLevel)
</td>
<td>
@Html.DisplayFor(modelItem => item.HireDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new {
id=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new {
id=item.EmployeeID }) |
@Html.ActionLink("Delete", "Delete", new {
id=item.EmployeeID })
</td>
</tr>
}

</table> </body> </html>

You must remember that we can add more list items to show department information in
details view if required. Pay special attention to new { id=item.EmployeeID }.
It is known as routing values of Action Link that are being passed to
controller method. We will receive parameter in Edit/Delete/Details
action method with same name (and preferably with same data type or
data type which must be convertible to integer) specified in view (id
in our case).
@Html.ActionLink("Details", "Details", new { id=item.EmployeeID })
will be rendered as href tag with text details. This html helper has
three parameters. First one is used to specify link text, second on is
used to specify Action of Controller class and third one is used to
specify route values(Consult RouteConfig class for more details). On
click of this this link Details method of same controller
(EmployeeController) will be rendered. Create Following method in
Employee Controller.
public ActionResult Details(Int64 id)
{
EmployeeEntity entity = new EmployeeEntity();
Employee employee= entity.GetSingleEmployee(id);
return View(employee);
}
Right click on the Details method and add view for Details of single
Employee as shown if Figure 3.
Figure 3

Following is the code for Details view.


@model MVCDemo.Models.Employee

@{
Layout = null;
}

<!DOCTYPE html>

<html> <head>
<meta name="viewport" content="width=device-width" />
<title>Details</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head> <body> <div>
<h4>Employee</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.FirstName)
</dt>

<dd>
@Html.DisplayFor(model => model.FirstName)
</dd>

<dt>
@Html.DisplayNameFor(model => model.LastName)
</dt>

<dd>
@Html.DisplayFor(model => model.LastName)
</dd>

<dt>
@Html.DisplayNameFor(model => model.Gender)
</dt>

<dd>
@Html.DisplayFor(model => model.Gender)
</dd>

<dt>
@Html.DisplayNameFor(model => model.City)
</dt>

<dd>
@Html.DisplayFor(model => model.City)
</dd>

<dt>
@Html.DisplayNameFor(model => model.EmailAddress)
</dt>

<dd>
@Html.DisplayFor(model => model.EmailAddress)
</dd>

<dt>
@Html.DisplayNameFor(model => model.Salary)
</dt>

<dd>
@Html.DisplayFor(model => model.Salary)
</dd>

<dt>
@Html.DisplayNameFor(model => model.Age)
</dt>

<dd>
@Html.DisplayFor(model => model.Age)
</dd>

<dt>
@Html.DisplayNameFor(model => model.EducationLevel)
</dt>

<dd>
@Html.DisplayFor(model => model.EducationLevel)
</dd>

<dt>
@Html.DisplayNameFor(model => model.HireDate)
</dt>

<dd>
@Html.DisplayFor(model => model.HireDate)
</dd>

</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.EmployeeID
}) |
@Html.ActionLink("Back to List", "Index")
</p>
</body> </html>

Add following method in the EmployeeEntity class of DAL Folder.


public Employee GetSingleEmployee(Int64 id)

{
Employee employee=null;
sqlConnection = new SqlConnection(ConnectionString);
string query = @"select * from Employee inner join
Department on Employee.DepartmentID =
Department.DepartmentID where Employee.EmployeeId='"+id+"' ";

cmd = new SqlCommand(query, sqlConnection);


sqlConnection.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
if (dataReader.Read())
{
employee=new Employee
{
EmployeeID =
Convert.ToInt64(dataReader["EmployeeId"].ToString()),
FirstName = dataReader["FirstName"].ToString(),
LastName = dataReader["LastName"].ToString(),
Gender = dataReader["Gender"].ToString(),
City = dataReader["City"].ToString(),
EmailAddress = dataReader["EmailAddress"].ToString(),
Age =
Convert.ToInt32(dataReader["Age"].ToString()),
Salary =
Convert.ToInt32(dataReader["Salary"].ToString()),
EducationLevel =
Convert.ToInt32(dataReader["EducationLevel"].ToString()),
HireDate =
DateTime.Parse(dataReader["HireDate"].ToString()),
department = new Department
{
DepartmentID =
Convert.ToInt32(dataReader["departmentId"].ToString()),
Name = dataReader["Name"].ToString()
}
};
}
sqlConnection.Close();
return employee; }
Now we have to add action for Delete in Employee Controller as following.

[HttpPost]
public ActionResult Delete(Int64 id)
{
EmployeeEntity entity = new EmployeeEntity();
Employee employee = entity.DeleteEmployee(id); return
RedirectToAction("Index");
}

Pay special attention to return RedirectToAction("Index"). Here we are


calling the Index Action Method of same controller. There are many
overloaded version of this method.
We don’t want to delete a record using Get Request as it is not
recommended by Microsoft. Also, when search engines (like google)
index your page, they produce a GET request which might delete the
data from database. In general GET request should be free of any side-
effects, meaning it should not change the state.
Now change the already created index view with following code.

@model IEnumerable<MVCDemo.Models.Employee>

@{
Layout = null;
}

<!DOCTYPE html>

<html> <head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head> <body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.Gender)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.EmailAddress)
</th>
<th>
@Html.DisplayNameFor(model => model.Salary)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.EducationLevel)
</th>
<th>
@Html.DisplayNameFor(model => model.HireDate)
</th>
<th></th>
</tr>

@foreach (var item in Model)


{
using (Html.BeginForm("Delete", "Employee", new { id =
item.EmployeeID }))
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Gender)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailAddress)
</td>
<td>
@Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.EducationLevel)
</td>
<td>
@Html.DisplayFor(modelItem => item.HireDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id =
item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { id =
item.EmployeeID }) |
<input type="submit" value="Delete" class="btn btn-danger" onclick="return
confirm('Are you sure you want to delete this record?');"/>
</td>
</tr>
}
}
</table> </body> </html>

Write following code in the EmployeeEntity Class to delete the record


from Database.
public int DeleteEmployee(long id)
{
int effectedRows = 0;
try {
sqlConnection = new SqlConnection(ConnectionString);
string query = @"delete from employee where EmployeeId='"+id+"'";
sqlConnection.Open();
cmd = new SqlCommand(query, sqlConnection);
effectedRows = cmd.ExecuteNonQuery();
sqlConnection.Close(); return effectedRows;
}
catch (Exception exp)
{
return effectedRows;

}
}

Now we will discuss about Edit method in MVC Application.


First of all create an Action Method in Employee Controller. Following
is code for that method.
public ActionResult Edit(Int64 id)
{
EmployeeEntity entity = new EmployeeEntity();
Employee employee= entity.GetSingleEmployee(id);
ViewBag.DepartmentsList = getDepartmentList();
return View(employee); }

Right click on the Edit method to create and Edit view by selecting
Edit from template and Employee from model as shown in Figure 4.

Figure 4

Edit view will be created and you have to add one more field i.e.
dropdown list to permit super user change department of employee. We
are adding dropdown list because it will not be added during automatic
creation of Edit view. Don’t forget to add bootstrap CSS library. We
don’t want to change value of some fields (readonly) such as Email and
HireDate, so we have to use DisplayFor HtmlHelper for these fields.
Here is code for Edit view. You can safely use the code.
@model MVCDemo.Models.Employee

@{
Layout = null;
}
<!DOCTYPE html>

<html> <head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head> <body>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Edit Employee</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger"
})
@Html.HiddenFor(model => model.EmployeeID)

<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName,
"", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName,
"", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Gender, htmlAttributes: new
{ @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Gender, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Gender, "",
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.EmailAddress,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DisplayFor(model => model.EmailAddress, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.EmailAddress, "", new {
@class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Salary, htmlAttributes: new
{ @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Salary, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Salary, "",
new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new
{ @class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.EducationLevel,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EducationLevel, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.EducationLevel, "", new {
@class = "text-danger" })
</div>
</div>

<div class="form-group">
@Html.LabelFor(model => model.HireDate, htmlAttributes:
new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DisplayFor (model => model.HireDate, new {
htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.HireDate,
"", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.department.DepartmentID,
htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model =>
model.department.DepartmentID,
(List<SelectListItem>)ViewBag.DepartmentsList)
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="update" class="btn
btndefault" /> </div>
</div>
</div>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body> </html>

When we do not specify parameters in Html.BeginForm() , default


controller is the same controller(Employee Controller in this case) ,
default Action is same Action(Edit in this case) and default Form
Method is POST. Add Method for Edit to handle post request in the
Employee Controller.
Add following code in the Employee Controller.
[HttpPost]
public ActionResult Edit(Employee employee)
{
if (ModelState.IsValid)
{
EmployeeEntity entity = new EmployeeEntity();
int rowCount = entity.UpdateEmployee(employee);
return RedirectToAction("Index");
}
ViewBag.DepartmentsList = getDepartmentList();
return View(employee);
}
Add following code in the EmployeeEntity Class.
public int UpdateEmployee(Employee employee)
{
int RowCount = 0;
try {
sqlConnection = new SqlConnection(ConnectionString);
string query = @"update Employee set
FirstName='"+employee.FirstName+"',LastName='"+employee.LastName+"',Ge
nder='"+employee.Gender+"',Age='"+employee.Age+"',EducationLevel='"+em
ployee.EducationLevel+"',Salary='"+employee.Salary+"',City='"+employee
.City+"', DepartmentId='"+employee.department.DepartmentID+"' where
EmployeeID='"+employee.EmployeeID+"'";
sqlConnection.Open();
cmd = new SqlCommand(query, sqlConnection);
RowCount = cmd.ExecuteNonQuery();
sqlConnection.Close(); return RowCount;
}
catch (Exception exp)
{
return RowCount;
}
}
Assignment #6
Dear students read the given lectures carefully as per the course objectives mentioned on the top and
carryout the assignment as per following instructions

1. Submission Date: Sunday 19-April-2020 at 11:59 PM.

2. You must prepare handwritten Assignment with implementation in the form of project.

3. Send it to respective course teacher (after scanning it) for assessment by email only.
Task: Create List view to show Mobile information. This view must contains Edit and Delete
Link Button. Also write code for delete as well as Edit buttons and create required views for edit
and delete. Write required code for edit and delete in MobileController.
Mobile class must have following fields:
1: IMEI Number 2: Operating System (android as well as iOS and populate dropdown from database
table named OS) 3: Released Date (Must not greater than today)
4: Color (length must be great than 2 and less than 15) 5: Weight in grams 6:
Model Number 7: Ram (Must be greater than 1 GB and less than 8 GB) 8:
Price (Must be greater than 10,000 and less than 20, 0000)

You might also like