首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

jQuery AJAX 提交表單至 ASP.NET MVC 3 控制器完整範例

     編輯:ASP.NET 基礎

前端使用 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"; // 示例
    }
}

關鍵點解析

項目說明
contentTypeapplication/json 告訴 MVC 使用 JsonValueProviderFactory 解析 Request Body
dataJSON.stringify({...}) 將 JS 物件序列化為 JSON 字串
dataTypejson 讓 jQuery 自動解析回應為 JS 物件
參數綁定MVC 3+ 內建支援 JSON 反序列化至 Action 參數(同名匹配)
防偽請求生產環境需加 @Html.AntiForgeryToken() + [ValidateAntiForgeryToken],AJAX 需在 Header 傳送 Token

進階:使用 ViewModel

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。

常見問題

  • 400 Bad Request:JSON 格式錯誤、屬性名不匹配、缺少 contentType。
  • 參數為 null:未設 contentType: 'application/json',導致 MVC 用 Form 解析器失敗。
  • 循環引用序列化失敗:回傳實體物件含導航屬性,改用匿名物件或 DTO 返回。

此模式適用於所有無刷新表單提交場景:登入、註冊、搜尋、刪除確認等。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved