我正在使用以下功能来编辑员工记录。
public async Task<ActionResult> Edit([Bind(Include = "Id,EmployeeId,Name,FatherName,JoiningDate,EndDate,InitialSalary,CurrentSalary,CurrentAddress,PermanentAddress,ContactNumber,EmailId,Gender,DOB,DeptId,DigId,PFNo,BranchCode,Qualification")] Employee employee)
{
if (ModelState.IsValid)
{
string fileName = null;
if (Request.Files["ImageFileToUpload"]!=null)
{
///Saving the file to EmployeeImages folder with unique name.
HttpPostedFileBase file = Request.Files["ImageFileToUpload"];
fileName = UploadEmployeeImage(file);
}
else
{
///what condition I need to write here so that if no image selected then it will not update the image field?
///if I am writing
fileName = db.Employees.Find(employee.Id).PhotoPath;
///it’s showing error.
}
employee.PhotoPath = fileName;
db.Entry(employee).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.DeptId = new SelectList(db.Departments, "DeptId", "DeptName", employee.DeptId);
ViewBag.DigId = new SelectList(db.Designations, "DegId", "DegName", employee.DigId);
ViewBag.BranchCode = new SelectList(db.Branches, "BranchId", "BranchName", employee.BranchCode);
return View(employee);
}
我想在选择图像时更新图像字段,否则不应更改员工图像,但其他记录可能会更改。
请在我的代码中建议我需要更新的内容。
答案 0 :(得分:2)
最后我得到了我的问题的解决方案。以下代码我用来解决我的问题。
[HttpPost]
[ValidateAntiForgeryToken]
[ActionName("Edit")]
public async Task<ActionResult> Edit_Post(int Id)
{
Employee employee = new Employee();
employee = db.Employees.FindAsync(Id).Result;
//if (ModelState.IsValid)
//{
string fileName = null;
if (Request.Files["ImageFileToUpload"].ContentLength >0)
{
var file = Request.Files["ImageFileToUpload"];
///Saving the file to EmployeeImages folder with unique name.
if (!string.IsNullOrEmpty(employee.PhotoPath))
{
DeleteEmployeeImage(employee.PhotoPath);
}
fileName = UploadEmployeeImage(file);
TryUpdateModel(employee);
employee.PhotoPath = fileName;
}
else
{
TryUpdateModel(employee, null, null, new string[] { "PhotoPath" });
}
if (employee.DigId <= 0)
{
ModelState.AddModelError("DigId", "Designation is required");
}
if (ModelState.IsValid)
{
db.Entry(employee).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.DeptIdList = new SelectList(db.Departments, "DeptId", "DeptName", employee.DeptId);
ViewBag.DigIdList = new SelectList(db.Designations, "DegId", "DegName", employee.DigId);
ViewBag.BranchCodeList = new SelectList(db.Branches, "BranchId", "BranchName", employee.BranchCode);
return View(employee);
}
答案 1 :(得分:0)
您可以在选择图像时设置路径。
if (Request.Files["ImageFileToUpload"]!=null)
{
///Saving the file to EmployeeImages folder with unique name.
HttpPostedFileBase file = Request.Files["ImageFileToUpload"];
fileName = UploadEmployeeImage(file);
employee.PhotoPath = !string.isNullOrWhiteSpace(fileName) ? fileName : employee.PhotoPath ;
}
//else
//{
// else part not required.
//}
db.Entry(employee).State = EntityState.Modified;
await db.SaveChangesAsync();