我想发布ajax调用以进行编辑记录。当我单击“更新”按钮时,它获取Employee_id的所有字段,但记录未在数据库中更新。
[HttpGet]
public ActionResult Edit(int Employee_id) //this view will show records in popup
{
List<Employee_And_Department> empdept = new List<Employee_And_Department>();
SqlConnection conn = new SqlConnection(connnString);
var query = ("select Employee.Employee_id,Employee.Name,Employee.Contact,Department.Department_id,Department.Department_Name,Department.Salary,Department.Employee_id from Employee inner join Department on Employee.Employee_id = Department.Employee_id where Employee.Employee_id =" + Employee_id);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Employee_And_Department objEmployeeAndDepartment = new Employee_And_Department();
objEmployeeAndDepartment.Employee_id = Employee_id;
objEmployeeAndDepartment.Name = rdr["Name"].ToString();
objEmployeeAndDepartment.Contact = rdr["Contact"].ToString();
objEmployeeAndDepartment.Department_id = Convert.ToInt32(rdr["Department_id"]);
objEmployeeAndDepartment.Department_Name = rdr["Department_Name"].ToString();
objEmployeeAndDepartment.Salary = Convert.ToInt32(rdr["Salary"]);
empdept.Add(objEmployeeAndDepartment);
}
return PartialView("Partial1", empdept[0]);
}
[HttpPost]
public ActionResult Edit(Employee_And_Department objEmployeeDepartment)
{
using (SqlConnection conn = new SqlConnection(connnString))
{
conn.Open();
var query = ("update Employee set Name=@Name,Contact=@Contact where Employee_id=@Employee_id");
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Employee_id", objEmployeeDepartment.Employee_id);
cmd.Parameters.AddWithValue("@Name", objEmployeeDepartment.Name);
cmd.Parameters.AddWithValue("@Contact", objEmployeeDepartment.Contact);
cmd.ExecuteNonQuery();
}
var query1 = ("update Department set Department_Name=@Department_Name,Salary=@Salary where Employee_id=@Employee_id");
using(SqlCommand cmd=new SqlCommand(query1,conn))
{
cmd.Parameters.AddWithValue("@Employee_id", objEmployeeDepartment.Employee_id);
cmd.Parameters.AddWithValue("@Department_id", objEmployeeDepartment.Department_id);
cmd.Parameters.AddWithValue("@Department_Name", objEmployeeDepartment.Department_Name);
cmd.Parameters.AddWithValue("@Salary", objEmployeeDepartment.Salary);
cmd.ExecuteNonQuery();
}
conn.Close();
}
return RedirectToAction("ListofEmployees");
}
PostCall的部分视图脚本
<script>
$(document).ready(function () {
$("#btnSubmit").click(function () {
$("#loaderDiv").show();
var myformdata = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Test/Edit",
data: myformdata,
success: function () {
$("#loaderDiv").hide();
$("#myModal").modal("hide");
window.location.href = "/Test/ListofEmployees";
}
})
})
})
</script>