public class CustomersController : Controller
{
// GET: Customers
[HttpGet]
public ActionResult Customer()
{
ViewBag.Customers = listofCustomer();
return View();
}
[HttpPost]
public ActionResult Customer(Customers cust)
{
if (cust != null)
{
var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(connection);
string SqlQuery = string.Empty;
if (cust.CustId > 0)
{
SqlQuery = "Update Customers set Firstname=@Firstname,LastName=@LastName,Role=@Role where customerId=@customerId";
}
else
{
SqlQuery = "Insert into Customers(Firstname,LastName,Role) values(@Firstname,@LastName,@Role)";
}
SqlCommand cmd = new SqlCommand(SqlQuery, con);
cmd.Parameters.Add("@customerId", SqlDbType.VarChar).Value = cust.CustId;
cmd.Parameters.Add("@Firstname", SqlDbType.VarChar).Value = cust.Firstname;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = cust.LastName;
cmd.Parameters.Add("@Role", SqlDbType.VarChar).Value = cust.Role;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
ViewBag.Customers = listofCustomer();
}
ModelState.Clear();
return View();
}
public ActionResult Delete(int? id)
{
var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Delete from Customers where customerId=@customerId", con);
cmd.Parameters.Add("@customerId", SqlDbType.VarChar).Value = id;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
ViewBag.Customers = listofCustomer();
return View("Customer");
}
public ActionResult Edit(int? id)
{
var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select * from Customers where customerId=@customerId", con);
cmd.Parameters.Add("@customerId", SqlDbType.VarChar).Value = id;
Customers customer = new Customers();
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
if (idr.HasRows)
{
if (idr.Read())
{
customer.CustId = Convert.ToInt32(idr["customerId"]);
customer.Firstname = Convert.ToString(idr["Firstname"]);
customer.LastName = Convert.ToString(idr["LastName"]);
customer.Role = Convert.ToString(idr["Role"]);
}
}
con.Close();
ViewBag.Customers = listofCustomer();
return View("Customer", customer);
}
[NonAction]
private List<Customers> listofCustomer()
{
var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand("Select * From Customers", con);
con.Open();
SqlDataReader idr = cmd.ExecuteReader();
List<Customers> customers = new List<Customers>();
if (idr.HasRows)
{
while (idr.Read())
{
customers.Add(new Customers
{
CustId = Convert.ToInt32(idr["customerId"]),
Firstname = Convert.ToString(idr["Firstname"]),
LastName = Convert.ToString(idr["LastName"]),
Role = Convert.ToString(idr["Role"])
});
}
}
con.Close();
return customers;
}
}