如何在登录页将客户端数据传递至MVC控制器并保存到数据库?
实现登录页面数据传递到MVC控制器并保存到数据库的完整方案
首先先修正你现有代码里的小细节:按钮的onClick="Data()"和JS里的function data()大小写不一致,得统一成小写data()或者大写Data(),不然会出现函数找不到的问题。
接下来给你两种常用的实现方案,你可以根据项目需求选择:
方式一:传统表单提交(最简单直接)
这种方式不需要额外写复杂的JS,浏览器会自动处理表单数据的提交。
1. 完善Login.cshtml的HTML结构
把用户名、密码输入框放在<form>标签里,指定提交的目标控制器、方法和请求方式:
@using (Html.BeginForm("Login", "Account", FormMethod.Post)) { <input type="text" id="username" name="KullaniciAdi" placeholder="用户名" /> <input type="password" id="password" name="Sifre" placeholder="密码" /> <button type="submit" class="btn-login">Giriş Yap</button> }
划重点:输入框的
name属性必须和控制器方法的参数名KullaniciAdi、Sifre完全一致,MVC的模型绑定才能自动把表单值映射到参数上。
如果不想用MVC的Html.BeginForm,也可以写原生HTML表单:
<form action="/Account/Login" method="post"> <input type="text" id="username" name="KullaniciAdi" placeholder="用户名" /> <input type="password" id="password" name="Sifre" placeholder="密码" /> <button type="submit" class="btn-login">Giriş Yap</button> </form>
这种情况下你之前写的JS函数可以不用,点击提交按钮后浏览器会自动把数据POST到指定的控制器方法。
2. 完善AccountController的Login方法
补充数据库保存逻辑,同时注意安全细节:
DBEntities dB = new DBEntities(); [HttpPost] public ActionResult Login(string KullaniciAdi, string Sifre) { // 先做基础输入验证 if (string.IsNullOrEmpty(KullaniciAdi) || string.IsNullOrEmpty(Sifre)) { ViewBag.Error = "用户名和密码不能为空"; return View(); } // 注意:实际项目绝对不能明文存密码!这里用BCrypt加密示例 string hashedPassword = BCrypt.Net.BCrypt.HashPassword(Sifre); // 创建用户实体并添加到数据库上下文 var newUser = new Profil { KullaniciAdi = KullaniciAdi, Sifre = hashedPassword }; try { dB.Profil.Add(newUser); dB.SaveChanges(); // 保存成功后设置Session并跳转首页 Session["KullaniciAdi"] = KullaniciAdi; return RedirectToAction("Index", "Home"); } catch (Exception ex) { ViewBag.Error = $"保存失败:{ex.Message}"; return View(); } }
重要提醒:明文存储密码是严重的安全漏洞!一定要用哈希算法(比如BCrypt,可通过NuGet安装
BCrypt.Net-Next包)加密后再存入数据库。
方式二:AJAX异步提交(无刷新提交数据)
如果想要页面不刷新就完成数据提交,适合做更友好的交互体验,这时候需要完善你的JS函数:
1. 完善Login.cshtml的JS和HTML
<input type="text" id="username" placeholder="用户名" /> <input type="password" id="password" placeholder="密码" /> <button type="button" class="btn-login" onClick="data()">Giriş Yap</button> <script type="text/javascript"> function data() { // 获取输入值 const username = document.getElementById("username").value; const password = document.getElementById("password").value; // 基础验证 if (!username || !password) { alert("用户名和密码不能为空"); return; } // 发送AJAX请求,记得带上CSRF令牌防止攻击 fetch('/Account/Login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'RequestVerificationToken': '@Html.AntiForgeryToken()' }, body: JSON.stringify({ KullaniciAdi: username, Sifre: password }) }) .then(response => response.json()) .then(result => { if (result.success) { alert('登录信息保存成功!'); window.location.href = '/Home/Index'; } else { alert(`提交失败:${result.message}`); } }) .catch(error => { alert(`请求出错:${error.message}`); }); } </script>
2. 完善AccountController的Login方法
因为AJAX传的是JSON数据,需要用模型类接收并加上[FromBody]特性,同时开启CSRF验证:
DBEntities dB = new DBEntities(); [HttpPost] [ValidateAntiForgeryToken] // 对应前端的CSRF令牌,必须添加 public ActionResult Login([FromBody] LoginModel model) { if (!ModelState.IsValid) { return Json(new { success = false, message = "数据格式不正确" }); } try { string hashedPassword = BCrypt.Net.BCrypt.HashPassword(model.Sifre); var newUser = new Profil { KullaniciAdi = model.KullaniciAdi, Sifre = hashedPassword }; dB.Profil.Add(newUser); dB.SaveChanges(); Session["KullaniciAdi"] = model.KullaniciAdi; return Json(new { success = true, message = "保存成功" }); } catch (Exception ex) { return Json(new { success = false, message = ex.Message }); } } // 定义接收参数的模型类(放在Models文件夹下) public class LoginModel { [Required(ErrorMessage = "用户名不能为空")] public string KullaniciAdi { get; set; } [Required(ErrorMessage = "密码不能为空")] public string Sifre { get; set; } }
用模型类接收参数更规范,还能通过数据注解(比如
[Required])实现自动验证。
额外注意事项
- 数据库操作一定要加
try-catch捕获异常,避免程序崩溃。 - 如果是生产环境,不要把具体的异常信息返回给前端,返回通用的错误提示即可。
- 可以给控制器的
DBEntities加上依赖注入,避免手动创建实例的资源浪费。
内容的提问来源于stack exchange,提问作者Nadide YILMAZ
相关产品推荐
相关产品推荐

