MVC+ExtJs之验证信息无缝结合

1.服务器端代码:

        /// <summary>
        /// 自定义Ext Ajax请求结果
        /// </summary>
        /// <param name="success">是否成功</param>
        /// <param name="value">结果</param>
        /// <returns></returns>
        protected ActionResult ExtJson(bool success)
        {
            return ExtJson(success, 0, string.Empty);
        }

        /// <summary>
        /// 自定义Ext Ajax请求结果
        /// </summary>
        /// <param name="success">是否成功</param>
        /// <param name="value">结果</param>
        /// <returns></returns>
        protected ActionResult ExtJson(bool success, object value)
        {
            return ExtJson(success, 0, value);
        }

        /// <summary>
        /// 自定义Ext Ajax请求结果
        /// </summary>
        /// <param name="success">是否成功</param>
        /// <param name="value">结果</param>
        /// <returns></returns>
        protected ActionResult ExtJson(bool success, int code, object value)
        {
            return Json(new { success = success, code = code, value = value }, "text/html", System.Text.Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 返回服务器端Model验证错误
        /// </summary>
        /// <returns></returns>
        protected ActionResult ModelError()
        {
            List<object> errors = new List<object>();
            foreach (var key in ModelState.Keys)
            {
                var state = ModelState[key];
                foreach (var error in state.Errors)
                {
                    errors.Add(new { id = key, msg = error.ErrorMessage });
                }
            }

            if (errors.Count > 0)
            {
                return ExtJson(false, errors);
            }

            return ExtJson(false, "未知错误,请检查输入!");
        }

action调用示例:

if (!ModelState.IsValid)
{
        return ModelError();
}

  

2.客户端代码

handler: function() {
    var form = theForm.getForm();
    if (form.isValid()) {
        form.submit({
            waitMsg: '正在提交...',
            success: function(form, action) {
                Ext.Msg.alert('成功', '保存成功!', function() {
                    win.hide();
                    store.loadPage();
                });
            },
            failure: function(form, action) {
                if (action.result) {
                    if (typeof(action.result.value) == 'string') Ext.Msg.alert('失败', action.result.value);
                    else if (action.result.value.constructor == Array) theForm.getForm().markInvalid(action.result.value);
                } else {
                    Ext.Msg.alert('失败', '未知错误');
                }
            }
        });
    }
}

 

posted @ 2011-09-18 10:51  ahui  阅读(1010)  评论(1编辑  收藏  举报