<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<html>
<head>
<title>AJAX 登入範例</title>
<link href="/Content/style.css" rel="stylesheet" />
<script src="/Scripts/jquery-1.8.3.min.js"></script>
</head>
<body>
<div class="loginCon">
<h2><span>會員登入</span></h2>
<form id="formData">
<div class="inputBox">
<input type="text" name="user" placeholder="帳號/手機" class="userId" />
</div>
<div class="inputBox">
<input type="password" name="pwd" placeholder="密碼" class="passwordStyle" />
</div>
<div class="warn" style="display:none">帳號或密碼錯誤!</div>
<div class="remember">
<label><input type="checkbox" name="remembered" /> 自動登入</label>
</div>
<button type="button" class="loginBtn">登入</button>
</form>
</div>
<script>
$(function () {
// Enter 送出
$('.userId, .passwordStyle').on('keyup', function (e) {
if (e.keyCode === 13) $('.loginBtn').trigger('click');
});
$('.loginBtn').on('click', function () {
$('.warn').hide();
var pwd = $('.passwordStyle').val();
if (!pwd) { $('.warn').text('請輸入密碼').show(); return; }
var data = $('#formData').serialize();
$.post('/Login/CheckLoginInfo', data, function (res) {
if (res.status === 1) {
window.location.href = '/MemberCenter/Index';
} else {
$('.warn').text('帳號或密碼錯誤!').show();
}
}, 'json').fail(function () {
$('.warn').text('系統忙碌,請稍後再試').show();
});
});
});
</script>
</body>
</html>
using System;
using System.Web.Mvc;
using System.Web.Security;
using MyApp.Models;
using MyApp.Services;
namespace MyApp.Controllers
{
public class LoginController : Controller
{
public ActionResult Index() => View();
[HttpPost]
public ActionResult CheckLoginInfo(string user, string pwd, string remembered)
{
try
{
if (string.IsNullOrWhiteSpace(user) || string.IsNullOrWhiteSpace(pwd))
return Json(new { status = 0 });
// 密碼雜湊(示範 MD5,生產環境請用 BCrypt)
pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "md5").ToLower();
// 查詢會員
var account = MemberInfoService.GetMemberIdForCheck(user, pwd);
if (account == null)
return Json(new { status = 0 });
// 登入成功:寫入 Session
FunSession.SetSession(account); // 自訂 Session 封裝
// 記住我:發送 Cookie
if (remembered == "on")
{
var cookie = new HttpCookie("LoginInfo", account.Id.ToString()) { Expires = DateTime.Now.AddDays(3) };
Response.Cookies.Add(cookie);
}
else
{
// 明確刪除 Cookie
var cookie = new HttpCookie("LoginInfo", "") { Expires = DateTime.Now.AddYears(-1) };
Response.Cookies.Add(cookie);
}
return Json(new { status = 1 });
}
catch (Exception ex)
{
// 記錄日誌
return Json(new { status = 0, msg = "伺服器錯誤" });
}
}
}
}
$('#formData').serialize() 自動收集所有 name 屬性欄位,產生 user=xxx&pwd=yyy&remembered=on 字串。(string user, string pwd, string remembered)。FormsAuthentication.HashPasswordForStoringInConfigFile(舊版相容),新專案建議改用 BCrypt.Net-Next 套件。FunSession.SetSession(account) 將使用者物件序列化存入 Session,方便全站存取。remembered == "on" 判斷核取方塊狀態,設定 3 天效期或立即過期刪除。try-catch 捕獲例外,回傳統一格式 JSON,前端 .fail() 處理網路層錯誤。[ValidateAntiForgeryToken] 配合 @Html.AntiForgeryToken() 防 CSRF。BCrypt 或 Argon2,拒絕 MD5/SHA 系列。Secure、HttpOnly、SameSite=Strict。此範例展示了 ASP.NET MVC 中 AJAX 登入的標準模式:前端無刷新提交 → 後端驗證回傳 JSON → 前端依狀態導向或提示。程式碼結構清晰、關注點分離,易於擴充為社群登入、雙因子驗證等進階功能。