ASP.NET MVC下Ajax.BeginForm方式无刷新提交表单的示例分析
创始人
2024-11-27 20:20:19
0次

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

数据库表字段会频繁更改扩展,而流行的重业务的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)
 
  
   
    
          Title             @Html.TextBoxFor(x => x.Name, new { @class = "form-control", placeholder = "Title" })       @Html.ValidationMessageFor(x => x.Name)      
     Type             @Html.DropDownListFor(x => x.DeliverableType,        new List {             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" })      
    
          Description             @Html.TextAreaFor(x => x.Description, new { @class = "form-control", rows = 4 })      
    
                 Weight      
    
          Phase             @Html.DropDownListFor(x => x.Phase,        new List {             new SelectListItem { Text = "Phase 1", Value = "1" },             new SelectListItem { Text = "Phase 2", Value = "2" },             new SelectListItem { Text = "Phase 3", Value = "3" },             new SelectListItem { Text = "Phase 4", Value = "4" },             new SelectListItem { Text = "Phase 5", Value = "5" },        },        new { @class = "form-control" })      
     First                   
                  
               Detail             @Html.TextBoxFor(x => x.Detail, new { @class = "form-control", placeholder = "Detail" })       @Html.ValidationMessageFor(x => x.Detail)            Second                                                      Size             @Html.TextBoxFor(x => x.Size, new { @class = "form-control", placeholder = "Size" })            Third                                                      WBS Code             @Html.TextBoxFor(x => x.WbsNumber, new { @class = "form-control", placeholder = "WBS Code" })            Fourth                                                      Room             @Html.DropDownListFor(x => x.RoomId,            (ViewBag.Rooms as List),            new { @class = "form-control" })            A Variance                                   Area             @Html.DropDownListFor(x => x.AreaId,            (ViewBag.Areas as List),            new { @class = "form-control" })            B Variance                                   Comments                                                  Documents                                  File Name          Revision          Date                                            P-001.pdf          01          03/15/2017                                                     @if ( Request["action"] != "View" ) {      Save    }     Close         }  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   });  });

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


  
 
 
  
 

 
 
 

后端代码————

[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();
   }
  }

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...