前端使用 jQuery $.ajax 以 JSON 格式提交登入表單,後端 MVC 3 控制器接收模型綁定參數,返回 JSON 結果,實現無刷新登入體驗。
<div>
<input type="text" id="account" placeholder="帳號" />
<input type="password" id="psword" placeholder="密碼" />
<button id="btnLogin">登入</button>
<span id="msg" style="color:red"></span>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$("#btnLogin").click(function () {
var account = $("#account").val().trim();
var psword = $("#psword").val();
if (!account || !psword) { $("#msg").text("請輸入帳號密碼"); return; }
$.ajax({
url: '/Home/Login',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ account: account, psword: psword }),
dataType: 'json',
success: function (data) {
if (data.success) {
window.location.href = data.redirectUrl || '/Home/Index';
} else {
$("#msg").text(data.message || "登入失敗");
}
},
error: function (xhr) {
$("#msg").text("請求異常:" + xhr.status);
}
});
});
});
</script>
public class HomeController : Controller
{
[HttpPost]
public JsonResult Login(string account, string psword)
{
// 模型綁定自動映射 JSON 屬性到參數
if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(psword))
return Json(new { success = false, message = "帳號密碼不可為空" });
// 真實專案:呼叫 Service 驗證、密碼雜湊比對、建立 FormsAuthentication Ticket
bool isValid = ValidateUser(account, psword); // 自行實作
if (isValid)
{
FormsAuthentication.SetAuthCookie(account, false);
return Json(new { success = true, redirectUrl = Url.Action("Index", "Home") });
}
else
{
return Json(new { success = false, message = "帳號或密碼錯誤" });
}
}
private bool ValidateUser(string account, string psword)
{
// 對接資料庫、Identity、LDAP 等
return account == "admin" && psword == "123456"; // 示例
}
}
| 項目 | 說明 |
|---|---|
| contentType | application/json 告訴 MVC 使用 JsonValueProviderFactory 解析 Request Body |
| data | JSON.stringify({...}) 將 JS 物件序列化為 JSON 字串 |
| dataType | json 讓 jQuery 自動解析回應為 JS 物件 |
| 參數綁定 | MVC 3+ 內建支援 JSON 反序列化至 Action 參數(同名匹配) |
| 防偽請求 | 生產環境需加 @Html.AntiForgeryToken() + [ValidateAntiForgeryToken],AJAX 需在 Header 傳送 Token |
public class LoginVm
{
[Required] public string Account { get; set; }
[Required, DataType(DataType.Password)] public string Password { get; set; }
public bool RememberMe { get; set; }
}
[HttpPost]
public JsonResult Login(LoginVm model)
{
if (!ModelState.IsValid)
return Json(new { success = false, errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage) });
// ...
}
前端 data: JSON.stringify({ Account: ..., Password: ..., RememberMe: true }),MVC 自動綁定至 LoginVm。
contentType。contentType: 'application/json',導致 MVC 用 Form 解析器失敗。此模式適用於所有無刷新表單提交場景:登入、註冊、搜尋、刪除確認等。