ASP.NET MVC:如何在假期申请表单中使用登录用户的EmployeeID
解决方法:自动填充登录用户的EmployeeID替代下拉框
咱们一步步来调整代码,从Controller到View,确保整个流程顺畅且安全:
1. 修正Create GET方法的逻辑
你原来的Create GET方法里,获取EmployeeID的代码写在了return View();之后,这部分代码永远不会执行到,得先调整顺序,同时把获取到的用户信息传递给View:
public ActionResult Create() { // 先获取登录用户的完整信息 string name = Session["Name"].ToString(); var employee = db.Employees.FirstOrDefault(s => s.Email.Equals(name)); // 处理找不到用户的异常情况 if (employee == null) { return RedirectToAction("AccessDenied", "Home"); } // 实例化假期申请模型,自动填充EmployeeID var holidayRequest = new HolidayRequestForm { EmployeeID = employee.EmployeeID }; // 把用户姓名传到View用于显示 ViewBag.EmployeeName = employee.FullName; return View(holidayRequest); }
这里用FirstOrDefault直接获取完整的Employee对象,既可以拿到ID填充模型,还能顺便获取用户姓名用来在页面展示。
2. 修改View,替换下拉框为显示字段+隐藏域
原来的下拉框要改成只读的姓名展示+隐藏的ID字段,用户能看到自己的身份,但不能修改,同时ID会自动提交到后台:
把原来的EmployeeID下拉框代码块:
<div class="form-group"> @Html.LabelFor(model => model.EmployeeID, "Employee Name", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.DropDownList("EmployeeID", null, htmlAttributes: new { @class = "form-control" }) @Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" }) </div> </div>
替换成:
<div class="form-group"> @Html.LabelFor(model => model.EmployeeID, "Employee Name", htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <!-- 显示登录用户姓名,设置为只读 --> <input type="text" class="form-control" value="@ViewBag.EmployeeName" readonly /> <!-- 隐藏字段传递EmployeeID,提交时自动带至后台 --> @Html.HiddenFor(model => model.EmployeeID) @Html.ValidationMessageFor(model => model.EmployeeID, "", new { @class = "text-danger" }) </div> </div>
3. 增强POST方法的安全性
你的POST方法已经在Bind里包含了EmployeeID,但为了防止前端篡改隐藏字段,建议在后台再做一次验证:
[HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "RequestID,EmployeeID,StartDate,FinishDate,HoursTaken,Comments,YearCreated,MonthCreated,DayCreated,YearOfHoliday,Approved")] HolidayRequestForm holidayRequestForm) { // 验证提交的EmployeeID是否属于当前登录用户 string name = Session["Name"].ToString(); var employee = db.Employees.FirstOrDefault(s => s.Email.Equals(name)); if (employee == null || holidayRequestForm.EmployeeID != employee.EmployeeID) { ModelState.AddModelError("", "Invalid employee information."); ViewBag.EmployeeName = employee?.FullName; return View(holidayRequestForm); } if (ModelState.IsValid) { db.HolidayRequestForms.Add(holidayRequestForm); db.SaveChanges(); SendMailToAreaManager(); SendMailToManager(); return RedirectToAction("Index","Calendar"); } // 验证失败时重新传递用户姓名 ViewBag.EmployeeName = employee.FullName; return View(holidayRequestForm); }
这一步能有效防止恶意用户通过修改前端代码冒充他人提交申请。
内容的提问来源于stack exchange,提问作者Conor8630
相关产品推荐
相关产品推荐

