在 MVC 與 jQuery 協作的 B/S 系統中,前後端溝通的關鍵在於定義一個標準化的傳輸物件。本文採用 JSonMessage 類別作為統一回應格式,涵蓋執行狀態、標題、內容、導向 URL 以及回呼資料等欄位:
public class JSonMessage {
public int result { get; set; } // 0:錯誤 1:正確 2:提示 3:警告
public string title { get; set; } // Lightbox 視窗標題
public string content { get; set; } // 訊息具體內容
public string redirect { get; set; } // 彈出後自動導向的目標頁面
public object callBackData { get; set; } // 客戶端所需資料(如新增紀錄的 ID 或完整 Model)
}
控制器回傳 JsonResult 時,前端回呼函式即可直接取得這個物件的 JSON 表現。特別注意:若表單包含檔案上傳(multipart/form-data),瀏覽器無法直接解析 JSON 回應,此時需改用 JavaScriptSerializer 將物件序列化為純字串輸出。
為了避免引入龐大的第三方套件,作者實作了簡易的 $.fn.showMsg 外掛,支援依據 result 代碼自動切換樣式、顯示預設成功訊息、執行成功/失敗回呼,以及 3 秒自動淡出:
(function($) {
$.fn.showMsg = function(model, callback, fail) {
var me = this;
if (me.length === 0) {
$("body").append("<div id='" + me.selector.replace("#", "") + "'></div>");
$(me.selector).showMsg(model, callback);
return;
}
if (!model) return;
model.content = (model.result === 1 && !model.content) ? "操作成功!" : model.content;
me.html(model.content).removeClass().addClass("message_" + model.result).show(100);
if (model.result === 1 && fail) fail(model);
if (model.result === 1 && callback) callback(model);
setTimeout(function() {
if (me.css("display") !== "none") me.hide(100);
}, 3000);
return me;
};
})(jQuery);
所有視覺呈現(定位、動畫、圖示)均交由 CSS 控制,JS 僅負責狀態切換,符合關注點分離原則。
回呼函式在「彈窗表單提交 → 關閉彈窗 → 刷新父頁面列表」的流程中扮演關鍵角色。配合 redirect 屬性,還能實現無重整的頁面跳轉與歷史堆疊管理(前進/後退),極大提升單頁應用體驗。
驗證邏輯採用「HTML5 自訂屬性 + jQuery 遍歷」模式,支援非空、正則、最小長度等規則:
isnull="0":必填欄位regex:正則運算式minlength:最小長度dvalue:預設佔位值核心程式碼分為兩階段:
$.fn.inputValidate = function() {
$("input,select,textarea", this).each(function() {
var me = $(this), isnull = me.attr("isnull") || "1", dvalue = me.attr("dvalue");
me.focus(function() { if (this.value === "") $(this).inputRemove(); });
me.keyup(function() { if (this.value === "") $(this).inputRemove(); });
// ① 非空檢查
if (isnull === "0") {
me.blur(function() {
if ($(this).val() === "" || $(this).val() === dvalue) $(this).inputError("此項必須填寫!");
else $(this).inputRight();
});
}
// ② 正則驗證
var regexValue = me.attr("regex");
if (regexValue !== undefined) {
me.blur(function() {
var re = new RegExp(regexValue, "ig");
if (this.value !== "" && !re.test(this.value)) { me.inputError("格式不正確!"); return false; }
else me.inputRight();
});
}
// ③ 最小長度
var minLength = parseInt(me.attr("minlength")) || 0;
if (minLength) {
me.blur(function() {
if (me.val() !== null && me.val().length < minLength) me.inputError("長度不能小於 " + minLength);
});
}
});
};
$.fn.submitValidate = function() {
var result = true;
$("input:visible,select:visible,textarea:visible", this).each(function() {
var me = $(this), thisValue = "";
if (me.attr("type") === "radio" || me.attr("type") === "checkbox")
thisValue = $("input[name='" + this.name + "']:checked").val();
else thisValue = me.val();
// 必填檢查
if (me.attr("isnull") === "0") {
if (thisValue === "" || (thisValue !== "" && thisValue === me.attr("dvalue"))) {
me.inputError("此項必須填寫!"); return result = false;
} else me.inputRight();
}
// 格式檢查
if (thisValue !== "") {
var reValue = me.attr("regex");
if (reValue !== undefined) {
var re = new RegExp(reValue, "ig");
if (!re.test(thisValue)) { me.inputError("格式不正確!"); return result = false; }
else me.inputRight();
}
}
});
return result;
};
$.fn.inputError = function(msg) {
this.inputRemove();
$("span", this.parent()).hide();
this.parent().addClass("focus").append("<span class='error'>" + (msg || '') + "</span>");
};
$.fn.inputRight = function(msg) {
this.inputRemove();
$("span", this.parent()).hide();
this.parent().addClass("focus").append("<span class='right'>" + (msg || '') + "</span>");
};
$.fn.inputRemove = function() {
this.removeClass("focus");
$(".right,.error", this.parent()).remove();
$("span", this.parent()).show();
};
此架構將驗證規則宣告式地寫在 HTML 標籤上,JS 僅負責解析與執行,維護成本極低,且易於擴充自訂驗證規則。