.NET MVC如何将数据库数据加载到文本框并区分可编辑字段
问题排查及解决方案
1. 核心问题汇总
- 控制器中数据库上下文实例定义位置错误,Index方法无法正常调用db对象
- 控制器查询到数据后未传递给视图,且返回的全量用户列表类型和视图声明的单个User模型不匹配
- 没有根据当前登录用户筛选数据,直接查询了所有用户数据
- 未给需要不可编辑的字段添加只读属性,表单提交方法配置错误
2. 修复步骤
2.1 修正Home控制器代码
namespace MVC_Login_6Dec.Controllers { public class HomeController : Controller { // 将数据库上下文实例移到类级别最顶部,供所有方法调用 private LoginDatabaseEntities db = new LoginDatabaseEntities(); // GET: /Home/ public ActionResult Index() { // 重定向到业务逻辑页,也可以直接在Index内实现逻辑 return RedirectToAction("GetList"); } public ActionResult GetList() { // 从Session中获取当前登录用户ID,查询单条对应用户数据 int userId = Convert.ToInt32(Session["userID"]); var userData = db.Users.FirstOrDefault(u => u.UserID == userId); // 将查询到的用户数据传递给视图 return View(userData); } [HttpPost] public ActionResult GetList(User model) { if(ModelState.IsValid) { // 保存用户提交的可编辑字段逻辑,可根据实际需求调整更新字段 int userId = Convert.ToInt32(Session["userID"]); var userInDb = db.Users.FirstOrDefault(u => u.UserID == userId); // 示例:假设Address、LineManager、Designation为可编辑字段,其余固化字段不更新 userInDb.Address = model.Address; userInDb.LineManager = model.LineManager; userInDb.Designation = model.Designation; db.SaveChanges(); } return View(model); } } }
2.2 修正视图代码
@model MVC_Login_6Dec.Models.User @{ Layout = null; if (Session["userID"] == null) { Response.Redirect("~/Login/Index"); } } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>员工信息</title> </head> <body> <div> <h1>Employee Details</h1> <div> <h4>UserName: @Session["userName"].ToString()</h4> </div> <div> <a href="@Url.Action("Logout","Login")">Logout</a> </div> <br> </div> <div> @using (Html.BeginForm("GetList", "Home", FormMethod.Post)) { <table> <!-- 以下为不可编辑的固化字段,添加readonly属性 --> <tr> <td>@Html.LabelFor(Model => Model.Name)</td> <td>@Html.TextBoxFor(Model => Model.Name, new { @readonly = "readonly" })</td> </tr> <tr> <td>@Html.LabelFor(Model => Model.FatherName)</td> <td>@Html.TextBoxFor(Model => Model.FatherName, new { @readonly = "readonly" })</td> </tr> <tr> <td>@Html.LabelFor(Model => Model.CNIC)</td> <td>@Html.TextBoxFor(Model => Model.CNIC, new { @readonly = "readonly" })</td> </tr> <tr> <td>@Html.LabelFor(Model => Model.Department)</td> <td>@Html.TextBoxFor(Model => Model.Department, new { @readonly = "readonly" })</td> </tr> <!-- 以下为可编辑字段,无需添加只读属性 --> <tr> <td>@Html.LabelFor(Model => Model.Address)</td> <td>@Html.TextBoxFor(Model => Model.Address)</td> </tr> <tr> <td>@Html.LabelFor(Model => Model.LineManager)</td> <td>@Html.TextBoxFor(Model => Model.LineManager)</td> </tr> <tr> <td>@Html.LabelFor(Model => Model.Designation)</td> <td>@Html.TextBoxFor(Model => Model.Designation)</td> </tr> </table> <button type="submit">保存修改</button> } </div> </body> </html>
3. 额外注意事项
- 可编辑字段可根据业务需求灵活调整,只需给不需要编辑的字段加上
@readonly = "readonly"属性即可 - 建议添加防伪造令牌校验:视图表单内添加
@Html.AntiForgeryToken(),对应Post方法上添加[ValidateAntiForgeryToken]注解 - Session登录校验逻辑建议抽成公共过滤器,避免每个页面重复编写
内容的提问来源于stack exchange,提问作者K H A N
相关产品推荐
相关产品推荐

