ASP.NET MVC下Ajax.BeginForm方式无刷新提交表单

有时候,不得不考虑到以下场景问题:

数据库表字段会频繁更改扩展,而流行的重业务的js框架过于依赖json数据接口,导致的问题是,数据库表更改 -> 数据接口更改 -> 前段框架逻辑更改。。。

一不小心就陷入坑坑洼洼。

这样的话,原来纯ASP.NET MVC绑定的方式,还是可以一用的,因为该方式不用再为那么多js代码烦恼。

不好意思,前面自说自话啊,直接上干货代码了————

Ajax.BeginForm
@{
    Layout = null;
    var ajaxOptions = new AjaxOptions {
        UpdateTargetId = "updateHolder",
        OnBegin = "DeliverableEdit.onBegin",
        OnFailure = "DeliverableEdit.onFailure",
        OnSuccess = "DeliverableEdit.onSuccess",
        OnComplete = "DeliverableEdit.onComplete",
        HttpMethod = "Post"
    };
}
@using ( Ajax.BeginForm("Save", "DesignDeliverable", null, ajaxOptions, new { @class = "form-horizontal", id = "editForm" }) ) {
    @Html.HiddenFor(x => x.Id)
    @Html.HiddenFor(x => x.TaskCode)
    @Html.HiddenFor(x => x.ShortName)

    <div class="container-fluid pad-15">
        <div class="row">
            <div class="col-xs-6">
                <div id="updateHolder" style="display:none;"></div>
                <div class="form-group">
                    <label class="col-sm-2 control-label">Title</label>
                    <div class="col-sm-4">
                        @Html.TextBoxFor(x => x.Name, new { @class = "form-control", placeholder = "Title" })
                        @Html.ValidationMessageFor(x => x.Name)
                    </div>
                    <label class="col-sm-2 control-label">Type</label>
                    <div class="col-sm-4">
                        @Html.DropDownListFor(x => x.DeliverableType,
                         new List<SelectListItem> {
                                                new SelectListItem { Text = "Type 1", Value = "1" },
                                                new SelectListItem { Text = "Type 2", Value = "2" },
                                                new SelectListItem { Text = "Type 3", Value = "3" },
                                                new SelectListItem { Text = "Type 4", Value = "4" },
                                                new SelectListItem { Text = "Type 5", Value = "5" },
                         },
                         new { @class = "form-control" })
                    </div>
                </div>
 
   。。。。
            </div>

            <div class="col-xs-6">
                <div class="form-group">
                    <div class="col-sm-12">
                        <label class="control-label">Documents</label>
                        <table class="table table-bordered table-hover table-condensed mt-10">
                            <thead>
                                <tr>
                                    <th>File Name</th>
                                    <th>Revision</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>P-001.pdf</td>
                                    <td>01</td>
                                    <td>03/15/2017</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="page_footer absolute-position">
        <div class="page_footer_inner page_footer_light text-right">
            @if ( Request["action"] != "View" ) {
                <button class="btn btn-primary" id="btnSave"><i class="fa fa-floppy-o fa-fw"></i> Save</button>
            }
            <button id="btnCancel" class="btn btn-default"><i class="fa fa-close fa-fw"></i> Close</button>
        </div>
        <span id="notification"></span>
    </div>
}
<script type="text/javascript">
    var DeliverableEdit = DeliverableEdit || {};
    (function (o) {
        o.timer = null;
        o.displayLoading = function (target) {
            var element = $(target);
            kendo.ui.progress(element, true);
            o.timer = setTimeout(function () {
                kendo.ui.progress(element, false);
            }, 50);
        };
        o.hideLoading = function (target) {
            setTimeout(function () {
                clearTimeout(o.timer);
            }, 50);
        };

        o.initializeValidation = function () {
            $.validator.setDefaults({
                showErrors: function (errorMap, errorList) {
                    $(".page_footer_inner button").removeProp("disabled", "disabled");

                    // Clean up any tooltips for valid elements
                    $.each(this.validElements(), function (index, element) {
                        var $element = $(element);

                        $element.data("title", "") // Clear the title - there is no error associated anymore
                            .removeClass("field-validation-error")
                            .tooltip("destroy");
                    });

                    // Create new tooltips for invalid elements
                    $.each(errorList, function (index, error) {
                        var $element = $(error.element);

                        $element.tooltip("destroy") // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
                            .data("title", error.message)
                            .data("placement", "bottom")
                            .addClass("field-validation-error")
                            .tooltip(); // Create a new tooltip based on the error messsage we just set in the title
                    });
                }
            });
            $.validator.unobtrusive.parse($("#editForm"));
        };

        o.showSuccess = function (msg) {
            $("#notification").data('kendoNotification').show(msg, "success");
        };
        o.showWarning = function (msg) {
            $("#notification").data('kendoNotification').show(msg, "warning");
        };

        // Events during the submit of Ajax.Form
        o.onBegin = function () {
            $(".page_footer_inner button").prop("disabled", "disabled");
            o.displayLoading($(".form-horizontal"));
        }
        o.onSuccess = function (data) {
            o.hideLoading(o.timer);
            if (!data || !data.code) {
                o.showWarning("Failure,please try it again.");
                return;
            }

            if (data && data.code) {
                gridView.refreshGrid();
                o.showSuccess("Saved successfully.");

                setTimeout(function () {
                    gridView.closeDeliverableDialog();
                }, 500);
            }
        }
        o.onFailure = function (request, error) {
            o.hideLoading(o.timer);
            o.showWarning("Failure,please try it again.");
        }
        o.onComplete = function (request, status) {
            o.hideLoading(o.timer);
            $(".page_footer_inner button").removeProp("disabled", "disabled");
        }
    })(DeliverableEdit);

    $(function () {
        // To fix jquery.validation invalid issue
        DeliverableEdit.initializeValidation();

        $("#btnCancel").click(function (e) {
            e.preventDefault();
            gridView.closeDeliverableDialog();
        });

        $("#btnSave").click(function (e) {
            e.preventDefault();
            $(".form-horizontal").submit();
            $(".page_footer_inner button").prop("disabled", "disabled");
        });

        $("#notification").kendoNotification({
            position: {
                pinned: true,
                top: 15,
                left: '50%'
            },
            autoHideAfter: 1000
        });
    });

</script>

记得引用对应的js库————

<link href="~/content/libs/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="~/content/libs/fa/css/font-awesome.min.css" rel="stylesheet" type="text/css" /> 

    <link href="~/content/app/css/site.css" rel="stylesheet" type="text/css" />
    <link href="~/content/app/css/bootstrap-extend.css" rel="stylesheet" type="text/css" />
    <link href="~/content/app/css/bootstrap-override.css" rel="stylesheet" type="text/css" /> 

    <script src="~/content/libs/jquery/jquery.min.js"></script>
<script src="~/content/libs/jquery/jquery.validate-vsdoc.js"></script>
    <script src="~/content/libs/jquery/jquery.validate.js"></script>
    <script src="~/content/libs/jquery/jquery.validate.unobtrusive.js"></script>
    <script src="~/Content/libs/jquery/jquery.unobtrusive-ajax.min.js"></script>

后端代码————

[Route("~/DesignDeliverable/Edit/{id?}")]
        [HttpGet]
        public ActionResult Edit(Guid? id) {
            using ( EmpsDbContext db = new EmpsDbContext() ) {
                DesignDeliverable entity = null;
                if ( id.HasValue ) {
                    entity = db.DesignDeliverables.SingleOrDefault(x => x.Id == id.Value);
                }
                else {
                    entity = new DesignDeliverable();
                }
                ViewBag.Rooms = RoomFacade.GetAll().Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
                ViewBag.Areas = AreaFacade.GetAll().Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList();
                return View(entity);
            }
        }

        [Route("~/DesignDeliverable/Save")]
        [HttpPost]
        public JsonResult Edit(DesignDeliverable model) {
            using ( EmpsDbContext db = new EmpsDbContext() ) {
                if ( !ModelState.IsValid ) {
                    return Error();
                }

                try {
                    model.GroupId = new Guid("e030c300-849c-4def-807e-a5b35cf144a8");   //todo: fix this hardcode
                    db.DesignDeliverables.AddOrUpdate(model);
                    db.SaveChanges();
                    return Success();
                }
                catch {
                    //TODO: to store the exception message
                }
                return Error();
            }
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值