ValuesController.cs (sending the HTTP request such as GET, POST, DELETE and etc):
public class ValuesController : ApiController
{
Database_Access_Data.db dblayer = new Database_Access_Data.db();
[HttpPost]
[Route("api/Values/SendLocation")]
public IHttpActionResult SendLocation([FromBody]Location cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.SendLocation(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
[HttpGet]
[Route("api/Values/GetLocationHistory")]
public DataSet GetLocationHistory()
{
DataSet ds = dblayer.GetLocationHistory();
return ds;
}
[HttpPost]
[Route("api/Values/SendDistance")]
public IHttpActionResult SendDistance([FromBody]Location cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.SendDistance(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
[HttpGet]
[Route("api/Values/GetUser")]
public DataSet GetUser()
{
DataSet ds = dblayer.GetUser();
return ds;
}
[HttpPost]
[Route("api/Values/FlagingDevice")]
public IHttpActionResult FlagingDevice([FromBody]Timer cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.FlagingDevice(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
[HttpPost]
[Route("api/Values/SendBox")]
public IHttpActionResult SendBox([FromBody]Box cs)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
dblayer.SendBox(cs);
return Ok("Success");
}
catch (Exception e)
{
return Ok("Something went Wrong" + e);
}
}
}
db.cs (used to call the stored procedure as well as sending the parameter):
public class db
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["localhost"].ConnectionString);
Location cs = new Location();
public void SendLocation(Location cs)
{
SqlCommand com = new SqlCommand("SendGPS",con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#DeviceImei", cs.DeviceImei);
com.Parameters.AddWithValue("#Latitude",cs.Latitude);
com.Parameters.AddWithValue("#Longitude",cs.Longitude);
com.Parameters.AddWithValue("#Distance", cs.Distance);
com.Parameters.AddWithValue("#LocationSend",cs.LocationSend);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
public DataSet GetLocationHistory()
{
SqlCommand com = new SqlCommand("GetLocationHistory", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public DataSet GetUser()
{
SqlCommand com = new SqlCommand("GetUser", con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
public void SendDistance(Location cs)
{
SqlCommand com = new SqlCommand("SendDistance", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#DeviceImei", cs.DeviceImei);
com.Parameters.AddWithValue("#Distance", cs.Distance);
com.Parameters.AddWithValue("#LocationSend", cs.LocationSend);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
public void FlagingDevice(Timer cs)
{
SqlCommand com = new SqlCommand("FlagingDevice", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Interval", cs.Interval);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
public void SendBox(Box cs)
{
SqlCommand com = new SqlCommand("SendBox", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Id", cs.Id);
com.Parameters.AddWithValue("#PollingStationID", cs.PollingStationID);
com.Parameters.AddWithValue("#DeviceImei", cs.DeviceImei);
con.Open();
com.Connection = con;
com.ExecuteNonQuery();
con.Close();
}
}
The stored procedure that used to return the data from the table:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[FlagingDevice]
#Interval INT
AS
DECLARE #Time DATETIME
IF #Interval = 5
BEGIN
SET #Time = (SELECT MAX(LocationSend) FROM dbo.Location)
SELECT D.imei, L.*, L1.*
FROM Device D
OUTER APPLY
(SELECT *
FROM dbo.Location L1
WHERE L1.DeviceImei = D.Imei
GROUP BY DeviceImei, Latitude, Longitude, Distance, LocationSend
HAVING DATEDIFF(MINUTE, LocationSend, #Time) <= #Interval) AS L
OUTER APPLY
(SELECT TOP 1 L4.ID AS 'Station', L3.Name
FROM [dbo].[ElectionDivision] L3, dbo.PollingStation L4
WHERE L.Latitude IS NOT NULL
AND L.Longitude IS NOT NULL
AND L.Distance IS NOT NULL
AND L.DeviceImei = D.ImeI) AS L1
END
ELSE IF #Interval = 0
BEGIN
SELECT D.imei, L.*, L1.*
FROM Device D
OUTER APPLY
(SELECT TOP 1 *
FROM dbo.Location L1
WHERE L1.DeviceImei = D.Imei
ORDER BY (LocationSend) DESC) AS L
OUTER APPLY
(SELECT TOP 1 L4.ID AS 'Station', L3.Name
FROM [dbo].[ElectionDivision] L3, dbo.PollingStation L4
WHERE L.Latitude IS NOT NULL
AND L.Longitude IS NOT NULL
AND L.Distance IS NOT NULL
AND L.DeviceImei = D.ImeI) AS L1
END
Update: I am using sqldatareader and put the data into a list but not sure how to return the FlaggingDevice Method as shown in the valuescontroller class. Should i be creating the list inside a class or something else. Any Suggestions ?
public List<FlagingDevice> FlagingDevice(FlagingDevice cs)
{
SqlCommand com = new SqlCommand("FlagingDevice", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Interval", cs.Interval);
con.Open();
com.Connection = con;
using (SqlDataReader sqlDataReader = com.ExecuteReader())
{
int movieGenreIDIndex = sqlDataReader.GetOrdinal("DeviceImei");
int movieIDIndex = sqlDataReader.GetOrdinal("Latitude");
int genreIDIndex = sqlDataReader.GetOrdinal("Longitude");
int genreIDIndex1 = sqlDataReader.GetOrdinal("Distance");
int genreIDIndex2 = sqlDataReader.GetOrdinal("LocationSend");
int genreIDIndex3 = sqlDataReader.GetOrdinal("Station");
int genreIDIndex4 = sqlDataReader.GetOrdinal("Name");
while (sqlDataReader.Read())
{
student.Add(new FlagingDevice()
{
DeviceImei = sqlDataReader.IsDBNull(movieGenreIDIndex) ? null : sqlDataReader.GetString(movieGenreIDIndex),
Latitude = sqlDataReader.IsDBNull(movieIDIndex) ? null : sqlDataReader.GetString(movieIDIndex),
Longitude = sqlDataReader.IsDBNull(genreIDIndex) ? null : sqlDataReader.GetString(genreIDIndex),
Distance = sqlDataReader.IsDBNull(genreIDIndex1) ? null : sqlDataReader.GetString(genreIDIndex1),
LocationSend = sqlDataReader.IsDBNull(genreIDIndex2) ? null : Convert.ToString(sqlDataReader["LocationSend"]),
Name = sqlDataReader.IsDBNull(genreIDIndex4) ? null : sqlDataReader.GetString(genreIDIndex4)
});
}
sqlDataReader.Close();
con.Close();
return student;
}
}
Related
Here is my SQL query:
CREATE PROCEDURE User_CRUD
#Action varchar(20),
#eno int,
#ename varchar(50),
#salary money
AS
IF #Action = 'Insert'
BEGIN
INSERT INTO employee (eno, ename, salary)
VALUES (#eno, #ename, #salary)
END
ELSE IF #Action = 'Update'
BEGIN
UPDATE employee
SET ename = #ename, salary = #salary
WHERE eno = #eno
END
ELSE IF #Action = 'Delete'
BEGIN
DELETE FROM employee
WHERE eno =#eno
END
ELSE IF #Action = 'Getemp'
BEGIN
SELECT *
FROM employee
END
ELSE IF #Action = 'Search'
BEGIN
SELECT ename, salary
FROM employee
WHERE eno = #eno
END
And here is my DAL class file:
public int AddEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Insert");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
cmd.Parameters.AddWithValue("#ename", e1.Ename);
cmd.Parameters.AddWithValue("#salary", e1.Salary);
e1.RollNo = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return e1.RollNo;
}
public int DeleteEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Delete");
cmd.Parameters.AddWithValue("#eno",e1.Eno);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public int UpdateEmployee(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Update");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
cmd.Parameters.AddWithValue("#ename", e1.Ename);
cmd.Parameters.AddWithValue("#salary", e1.Salary);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
public List<Models.Employee> GetEmployee()
{
List<Models.Employee> li = new List<Models.Employee>();
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
Models.Employee e1= new Models.Employee();
e1.RollNo = int.Parse(dr[0].ToString());
e1.Eno = int.Parse(dr[1].ToString());
e1.Ename = dr[2].ToString();
e1.Salary = double.Parse(dr[3].ToString());
cmd.Parameters.AddWithValue("#Action", "Getemp");
li.Add(e1);
}
}
return li;
}
public Models.Employee SearchEmp(Models.Employee e1)
{
con.Open();
SqlCommand cmd = new SqlCommand("User_CRUD", con);
cmd.CommandType= CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "Search");
cmd.Parameters.AddWithValue("#eno", e1.Eno);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
e1.Ename= dr[0].ToString();
e1.Salary= double.Parse(dr[1].ToString());
}
}
con.Close();
return e1;
}
When I try to perform some crud operation using single procedure it is showing error in GetEmployee() method like #Action method which was not supplied. SearchEmp() method is also showing the same error.
Can anyone help me with this?
Thanks in advance
I want to get data from database using two dates and get displayed in a chart.
I have used the link for the chart: https://www.aspsnippets.com/Articles/Google-Charts-in-ASPNet-MVC-Google-Pie-Doughnut-Chart-example-with-database-in-ASPNet-MVC.aspx
I have used the following video for the dates and getting data from the database: https://youtu.be/Rm4uiny5Ano
**CONTROLLER:**
public ActionResult Index()
{
mymodel db = new mymodel();
db.slips = AjaxMethod();
return View(db);
}
[HttpPost]
public JsonResult AjaxMethod(DateTime? start, DateTime? end)
{
string query = "SELECT [status], sum(total_amount) as Payment";
query += " FROM slips WHERE convert(varchar,date_paid, 101) BETWEEN '" + start + "' AND '" + end + "' and status='Paid' and inv_type='Valid' GROUP BY [status]";
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
List<object> chartData = new List<object>();
chartData.Add(new object[]
{
"status", "Payment"
});
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
chartData.Add(new object[]
{
sdr["status"], sdr["Payment"]
});
}
}
con.Close();
}
}
return Json(chartData);
}
private DbSet<slip> AjaxMethod()
{
throw new NotImplementedException();
}
It should display data from a database using a chart. But then there's an error that it throws on the "AjaxMethod()" method. I don't know if my code on the "Index" it's correct.
Chart Data
There is much more to this but just for your question and comment, you can create a Payment class and then a list of those and return that data. This should all be in the proper files (per class) to do it right.
How you use this list of payments I will leave up to you but you can start with this perhaps. Your model for example might include the text for the column headers.
using PaymentRepository;
public ActionResult Index()
{
PaymentModel db = new PaymentModel();
// the model might also do this directly
var chartData = PaymentRepository.GetPaidPaymentList();
db.slips = chartData;
return View(db);
}
[HttpPost]
public JsonResult GetPaymentList(DateTime start, DateTime end)
{
var chartData = PaymentRepository.GetPaymentByStatusList(start,end);
return Json(chartData);
}
// put in a class with using Payment
public class PaymentRepository
{
public static List<Payment> GetPaidPaymentList()
{
DateTime startDate = DateTime.MinValue;
DateTime endDate = DateTime.Now;
string status = "Paid";
return GetPaymentByStatusList(startDate, endDate, status = );
}
public static List<Payment> GetPaymentByStatusList(DateTime startDate, DateTime endDate, string status = "Paid")
{
List<Payment> payments = new List<Payment>();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Constring"].ConnectionString))
{
var sqlQuery = #"
SELECT [status], SUM(total_amount) as Payment
FROM slips
WHERE WHERE date_paid >= #startDate AND date_paid < #endDate
AND status = #status'
AND inv_type = 'Valid'
GROUP BY [status];
";
connection.Open();
using (SqlCommand cmd = new SqlCommand(sqlQuery, connection))
{
cmd.Parameters.Add("#startDate", System.Data.SqlDbType.DateTime);
cmd.Parameters["#startDate"].Value = startDate;
cmd.Parameters.Add("#endDate", System.Data.SqlDbType.DateTime);
cmd.Parameters["#endDate"].Value = endDate;
cmd.Parameters.Add("#status", System.Data.SqlDbType.VarChar);
cmd.Parameters["#status"].Value = status;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var payment = new Payment()
{status = (string)reader["status"], payment = (decimal)reader["Payment"]};
payments.Add(payment);
}
}
}
connection.Close();
}
return payments;
}
}
public class Payment
{
public string status
{
get;
set;
}
public decimal payment
{
get;
set;
}
}
Can you please help me see what is wrong with my code? If I run the stored procedure using the a parameter for Id, I get a result in SQL Server. But when I use the code below using the same value for Id, in my if(rdr.HasRows).. I get a false.
public Student Find(int key)
{
string connectionPath = ConnectionStrings.DbConnection;
Student student = null;
try
{
using(var sqlCon = new SqlConnection(connectionPath))
{
sqlCon.Open();
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
{
cmd.Parameters.AddWithValue("#Id", key);
using(var rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
{
if (rdr.HasRows)
{
while (rdr.Read())
{
student = new Student
{
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString(),
Gender = rdr["Gender"].ToString()
};
}
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return student;
}
If I try to get all records, I don't get any problems:
public IEnumerable<Student> GetAll()
{
var studentList = new List<Student>();
try
{
string connectionPath = ConnectionStrings.DbConnection;
using(var sqlCon = new SqlConnection(connectionPath))
{
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
{
sqlCon.Open();
using(var rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (rdr.Read())
{
studentList.Add
(
new Student
{
Id = Convert.ToInt32(rdr["Id"]),
Age = Convert.ToInt32(rdr["Age"]),
FirstName = rdr["FirstName"].ToString(),
LastName = rdr["LastName"].ToString()
}
);
}
}
}
}
}
catch(Exception ex)
{
throw ex;
}
return studentList;
}
This is using asp.net core
Your code for Find lacks the definition that this is a stored procedure that you're calling.
If you look at your GetAll, you have:
using(var cmd = new SqlCommand("Sp_GetStudents", sqlCon) { CommandType = CommandType.StoredProcedure})
defining this SqlCommand to be a stored procedure - this setting is missing from your Find code:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon))
I'm pretty sure it'll work if you add that:
using(var cmd = new SqlCommand("Sp_FindStudent", sqlCon) { CommandType = CommandType.StoredProcedure}))
I am sort of new to login feature for projects and am trying to do logins for my group, which consists of 3 users, namely Nurse, Patient and Pharmacist. I think I am about to complete the loin process but I have a problem with one of my methods, getPosition() in my LoginDAO.cs. So far, I have not done any login codes for patient and pharmacist as i will need my group mates' parts for it to work, but shown below is what I have done. Somehow, login(string nric, string pw) works, but not getPosition(string nric). This is the error that i get from my error log:
Exception: Must declare the scalar variable "#paraNRIC". Source: LoginDAO.getPosition
Thanks in advance :D
protected void btnLogin_Click(object sender, EventArgs e)
{
login login = new login();
login.nric = tbLoginID.Text;
login.pw = tbPassword.Text;
if (login.userLogin(login.nric, login.pw))
{
if (login.getPosition(login.nric) == "Nurse")
{
Response.Redirect("Nurse.aspx");
}
else if (login.getPosition(login.nric) == "Patient")
{
Response.Redirect("Patient.aspx");
}
else if (login.getPosition(login.nric) == "Pharmacist")
{
Response.Redirect("PharmacistDisplay.aspx");
}
}
else
{
lblErr.Text = "Invalid account.";
}
}
public bool login(string nric, string pw)
{
bool flag = false;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Password from Position");
sqlStr.AppendLine("Where NRIC = #paraNRIC");
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
cmd.Parameters.AddWithValue("#paraNRIC", nric);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt == null)
{
flag = false;
}
else
{
string dbhashedpw = dt.Rows[0]["Password"].ToString();
flag = Helper.VerifyHash(pw, "SHA512", dbhashedpw);
}
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("NurseDAO.login", sqlStr.ToString(), exc);
}
return flag;
}
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
myconn.Open();
result = cmd.ExecuteNonQuery();
dbPosition = dt.Rows[0]["Position"].ToString();
myconn.Close();
}
catch (Exception exc)
{
logManager log = new logManager();
log.addLog("LoginDAO.getPosition", sqlStr.ToString(), exc);
}
return dbPosition;
`}
Your error is here:
SqlCommand cmd = new SqlCommand();
// lines omitted
cmd.Parameters.AddWithValue("#paraNRIC", nric);
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
cmd = new SqlCommand(sqlStr.ToString(), myconn);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Note that you are instantiating cmd twice. The code adds the parameters to the first SqlCommand instance, but executes the second instance.
To resolve, ensure you declare the parameters on the instance of SqlCommand you invoke:
public string getPosition(string nric)
{
string dbPosition = "";
int result = 0;
// remove this line: SqlCommand cmd = new SqlCommand();
StringBuilder sqlStr = new StringBuilder();
sqlStr.AppendLine("SELECT Position from Position ");
sqlStr.AppendLine("where NRIC = #paraNRIC");
// move parameter declaration until after you declare cmd
try
{
SqlConnection myconn = new SqlConnection(DBConnect);
SqlCommand cmd = new SqlCommand(sqlStr.ToString(), myconn);
// add the parameters here:
cmd.Parameters.AddWithValue("#paraNRIC", nric);
// code continues
You could change this line
sqlStr.AppendLine("where NRIC = #paraNRIC");
To This
sqlStr.AppendLine("where NRIC = '" + nric + "'");
and avoid parameters altogether.
Hi I am beginner in MVC , I am trying to achieve CRUD operation in MVC using SQL with out Entity Framework or LINQ-SQL class. I done well with insert and getting the details of the selected table but when coming to Edit, details and delete I am confused how to perform so can some one help me out.
This is my code
Create a new Employee
public ActionResult Index(Test test)
{
try
{
if (ModelState.IsValid)
{
test.insert(test);
test.Name = "";
test.LastName = "";
}
}
catch (Exception)
{
}
return View(test);
}
Display all results
public ActionResult display()
{
Test tst = new Test();
return View(tst.getList());
}
This is my code in class file
public class Test
{
public int EmpID { get; set; }
[Required]
[DisplayName("Name")]
public string Name { get; set; }
[Required]
[DisplayName("LastName")]
public string LastName { get; set; }
string strConnection = ConfigurationManager.ConnectionStrings["SomeDataBase"].ConnectionString.ToString();
public void insert(Test test)
{
using (SqlConnection con = new SqlConnection(strConnection))
{
SqlCommand cmd = new SqlCommand("insert into Employee values('" + test.Name + "','" + test.LastName + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
public List<Test> getList()
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
public List<Test> edit(int id)
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
}
Can some one help me how to do the remaining operations like Details, Edit update and Delete.
for Details you can use
public Test details(int id)
{
Test _products = new Test();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
_products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_products.Name = dr["FirstName"].ToString();
_products.LastName = dr["LastName"].ToString();
}
catch(exception ex)
{
/* Do Some Stuff */
}
return _products;
}
And from your Controller
public ActionResult Details(int id)
{
Test tst = new Test();
return tst.Details(id);
}
for Edit you can use
public Bool Edit(test tst)
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("UPDATE TABLE Employee SET FirstName='"+tst.Name+"',Lastname='"+tst.LastName+"' where EmpID='" + tst.EmpId + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
return true;
}
catch(exception ex)
{
/* Do Some Stuff */
}
}
And from your Controller
public ActionResult Edit(test tsts)
{
Test tst = new Test();
return tst.Edit(tsts);
}
and proceed similarly for the rest of the cases