Hello Dear Readers, Here I am going to tell that how to
delete selected records in MVC with the help of classic ADO.NET. I am not going
to use Entity Framework.
Note: Please note
that I am assuming here that you are little bit aware of MVC and its contents.
If not, please get basic introduction of MVC.
So we can proceed now.
First of all Create Database in the SQL Server according to
the following picture-
Now fill some data in it –
Now, we will create action in Home Controller. It is not necessary that Controller should
be Home only. It can be
anyone according to your need.
[HttpGet]
public ActionResult showEmployees()
{
List<Employee> li = new List<Employee>();
DataTable dt = DAL.GetEmployee();
// method of DAL class
foreach (DataRow dr in dt.Rows)
{
Employee emp = new Employee() {
ID = Convert.ToInt32(dr["ID"]),
Ename = dr["ename"].ToString(),
Efather = dr["efather"].ToString(),
Eaddress = dr["eaddress"].ToString()
};
li.Add(emp);
}
return View(li);
}
Here DAL
is a class inside it we have created method to access data from database. The
details of method is –
public static DataTable GetEmployee()
{
SqlConnection con = new SqlConnection("Data Source= myserver;Initial
Catalog=DBFirst;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("select * from
e_data",
con);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
Note: It is not necessary that method should be of
static type. It may be non-static. In that case, You will have to create an
object of DAL class to access this method.
Model class –
namespace MVC18042016.Models
{
public class Employee
{
public int ID { get; set; }
public string Ename { get; set; }
public string Efather { get; set; }
public string Eaddress { get; set; }
}
}
Note: In each MVC
application, Model should be present for the properties. So that we can get or
set the data from/to database. Model is nothing special, it is a class having
properties.
Now create View of showEmployees Action by right click on it à Add view.
After creating view, we will change some code in the view. (1) Add border in table, so that we can
see data properly. (2) Add an extra
<th> and <td> for checkbox control. (3) Add submit button to post data.
See the code –
@model IEnumerable<MVC18042016.Models.Employee>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>showEmployees</title>
</head>
<body>
@using (Html.BeginForm("showEmployees","Home",FormMethod.Post))
{
<table class="table" border="1">
<tr>
<th>Select</th>
<th>
@Html.DisplayNameFor(model => model.Ename)
</th>
<th>
@Html.DisplayNameFor(model => model.Efather)
</th>
<th>
@Html.DisplayNameFor(model => model.Eaddress)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
<input
type="checkbox" name="deletedata" id="chk" value="@item.ID" />
</td>
<td>
@Html.DisplayFor(modelItem => item.Ename)
</td>
<td>
@Html.DisplayFor(modelItem => item.Efather)
</td>
<td>
@Html.DisplayFor(modelItem => item.Eaddress)
</td>
<td>
@Html.ActionLink("Edit", "Edit",
new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new
{ /*
id=item.PrimaryKey */
}) |
@Html.ActionLink("Delete", "Delete", new
{ /*
id=item.PrimaryKey */
})
</td>
</tr>
}
</table>
<input type="submit" name="submit" value="Delete Selected" />
}
</body>
</html>
See very carefully that I have associated checkbox with ID
property, so that we can get IDs of the records.
If you will run this application, it will be like this –
Now we will create ActionMethod for post action. The Code
is:
[HttpPost]
public ActionResult showEmployees(string[] deletedata)
{
foreach(string i in deletedata)
{
DAL.deletedatabyId(i);
}
return RedirectToAction("showEmployees");
}
In this code ‘deletedata’
is the name of checkbox control. You can check it in View. We have string array
because it will return collection of checkbox values.
The code of deletedatabyId(i) method is –
public static void deletedatabyId(string id)
{
SqlConnection con = new SqlConnection("Data Source=myserver;Initial
Catalog=DBFirst;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "Delete from e_data
where ID="+
Convert.ToInt32(id) +"";
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Note: Here, I want
tell again that static method is not necessary.
Some points to
remember: Here (1) I have
declared connection inside method only, but declare it in web.config file for
good approach. (2) I Have created logic
inside controller action method, but it is always a good approach to do this in
BAL(Business Access Layer) class.
Run the application and get the desired output.
Happy Coding.
Rudra Pratap Singh
Software
Engineer
singhrudrapratap29[at]gmail[dot]com
No comments:
Post a Comment