MVC+jQuery開發(fā)B/S系統(tǒng):表單提交
Jquery是一個優(yōu)秀的Javascrīpt框架。MVC是一個設計模式,它強制性的使應用程序的輸入、處理和輸出分開。今天我們就談如何用JQuery+MVC來處理表單的提交。
想達到的效果:
1、提交前的表單驗證
2、表單驗證
3、提交后的反饋信息
ok,先說一下工作的原理。
前臺<form action='xxx.aspx' method='post'></form>,action指定了接受表單的處理頁面。method這里我們只說post。 如果用ajax提交表單,自然xxx.aspx便是請求的url。ajax請求后的callback便是響應表單的提交結(jié)果(錯誤、成功),我們提交的反饋信息用一個 浮層(lightbox)來表示。 不至于用 alert(""); 這樣鐺鐺鐺很囧。
我們引入一個Jquery的插件http://www.malsup.com/jquery/form/#api 這是一個略有名氣的插件,方便易用。關(guān)于其用法,大家可以搜索下。
那么我們需要做的就是:
1、jquery.form.js的使用
2、lightbox的實現(xiàn)
3、如何驗證
代碼:
- $.fn.submitForm = function(args)
- {
- var url, id, callback, before;
- id = this.attr("id");
- if (typeof (args) == "string")
- {
- url = args;
- before = undefined;
- callback = undefined;
- }
- else
- {
- args = args || new Object();
- url = args.url || this.attr("action");
- if (typeof (args) == "function")
- {
- callback = args;
- }
- else
- {
- before = args.before;
- callback = args.callback;
- }
- }
- //輸入驗證
- this.inputValidate();
- //form沒有url 則是偽提交
- if (url == undefined || url == "")
- {
- $("#" + id).submit(function() {
- if ($("#" + id).submitValidate()==false)
- return false;
- //驗證成功就執(zhí)行callback
- callback();
- });
- }
- else
- {
- this.ajaxForm({
- url: url,
- beforeSubmit: function(a, f, o)
- {
- //提交驗證
- if ($("#" + id).submitValidate() == false)
- return false;
- if (before != undefined && before() == false) {
- return false;
- }
- o.dataType = "json";
- },
- success: function(data) {
- if (data == "" || data == null)
- {
- return false;
- }
- $("#myMsg").showMsg(data, callback);
- return false;
- }
- });
- }
- return this;
- };
上面的方法很簡單,就是form插件的使用,還有幾個我們需要實現(xiàn)的方法。(inputValidate,submitValiedate,ajaxMsg)
既然是ajax提交,我們則需要給客戶端一個反饋信息,然后用Lightbox呈現(xiàn)。
#p#
一:我們定義一個JsonMessage類
- public class JsonMessage
- {
- public int result { get; set; } //0錯誤 1正確 2提示 3警告
- public string title { get; set; }//Lightbox窗口的標題
- public string content { get; set; }//message的具體內(nèi)容
- public string redirect { get; set; }//彈出后自動跳轉(zhuǎn)的到哪里?
- public object callBackData { get; set; }//客戶端需要的數(shù)據(jù) 比如 一個新增的id或整個model
- }
MVC返回Json(jsonmsg1),客戶端的callback便可以得到這個對象的json格式。
(注意:如果是附件的表單提交,則不能識別JsonResult格式。具體我還沒有研究怎么回事,這種情況只能response一個json字符串,可以用System.Web.Script.Serialization.JavaScriptSerializer來序列化對象,也很方便。)
二:我們寫一個ajaxMsg來實現(xiàn)lightbox,這是我自己寫的Lightbox,比較簡陋,如果不喜歡,也可以用一些知名的插件。
代碼:
- (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 == undefined)
- return;
- model.content = model.result == 1 && model.content == undefined ? "操作成功!" : model.content;
- me.html(model.content);
- me.removeClass().addClass("message_" + model.result).show(100);
- if (model.result1 == 1 && fail != undefined)
- {
- fail(model);
- }
- if (model.result == 1 && callback != undefined)
- {
- callback(model);
- }
- setTimeout(function()
- {
- if (me.css("display") != "none")
- {
- me.hide(100);
- }
- }, 3000);
- return me;
- }
- })(jQuery);
Ajax消息的樣式完全可以用CSS來做,包括div的定位都可以在css里寫js代碼來實現(xiàn)。
不知道有沒有人能理解我這里的callback,我說一下他的用到的情況。 實際應用中我還有一個ajaxWin來實現(xiàn)彈窗,彈窗里的表單提交后一般需要關(guān)閉彈窗,然后更新一些數(shù)據(jù)(比如刷新列表)。這時就需要 submit后的callback動作。另外就是我目前還有使用到redirect這個屬性。呵呵,我之前的系統(tǒng)需要大量的跳轉(zhuǎn)處理,這些跳轉(zhuǎn)也是無刷新的,有一個數(shù)組來記錄訪問的地址。可以實現(xiàn)后退和前進。
三:好了,Lightbox已經(jīng)實現(xiàn)了,也能show出各種類型的信息了。
下面還剩下表單驗證。 其實表單驗證大有文章可做。我這也不能一一做到。目前只做了些簡單的驗證。以后會實現(xiàn)比較復雜的錯誤提示效果。其實這都是體力活,上面沒要求我也懶的弄。
驗證我采用的是給control一些自定義屬性,然后再判斷其值是否合法。
代碼:
- //輸入驗證
- $.fn.inputValidate = function() { $("input,select,textarea", this).each(function() {
- var me = $(this);
- var isnull = me.attr("isnull") || "1";
- var 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();
- });
- }
- //②正則注冊onchange事件
- var regexValue = me.attr("regex");
- if (regexValue != undefined) {
- var thisValue = me.val();
- me.blur(function() {
- var re = new RegExp(regexValue, "ig");
- if (this.value != "" && !re.test(this.value)) { me.inputError("格式不正確!");
- return result = false;
- } else me.inputRight();
- }); }
- //③最小長度
- var minLength = me.attr("minlength") || 0;
- if (minLength != undefined) minLength = parseInt(minLength);
- me.blur(function() {
- if (me.val() != null)
- if (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);
- var 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();
- }
- //② 是否符合格式 屬性為 regex 正則
- if (thisValue != "") {
- var reValue = $(this).attr("regex");
- if (reValue != undefined) {
- 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();
- //this.focus();
- $("span", this.parent()).hide();
- this.parent().addClass("focus").append("<span class='error'>" + (msg || '') + "</span>");
- }
- $.fn.inputRight = function(msg) {
- this.inputRemove();
- //this.focus();
- $("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();
- }
每一種方法,我們都應該從性能和發(fā)功效率上來考慮,要做到兩者兼得是很不容易的。通過本文作者的分析,希望會對你有所幫助。