欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-05 20:16:13
有时候,不得不考虑到以下场景问题: 数据库表字段会频繁更改扩展,而流行的重业务的js框架过于依赖json数据接口,导致的问题是,数据库表更改 -> 数据接口更改 -...

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

数据库表字段会频繁更改扩展,而流行的重业务的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 class="form-group">
     <label class="col-sm-2 control-label">description</label>
     <div class="col-sm-10">
      @html.textareafor(x => x.description, new { @class = "form-control", rows = 4 })
     </div>
    </div>
    <div class="form-group" style="margin-bottom: 3px;">
     <div class="col-sm-2 col-sm-offset-10">
      weight
     </div>
    </div>
    <div class="form-group">
     <label class="col-sm-2 control-label">phase</label>
     <div class="col-sm-3">
      @html.dropdownlistfor(x => x.phase,
       new list<selectlistitem> {
            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" })
     </div>
     <label class="col-sm-2 control-label">first</label>
     <div class="col-sm-3">
      <input class="form-control" type="text" placeholder="" />
     </div>
     <div class="col-sm-2">
      <input class="form-control" type="text" placeholder="weight" />
     </div>
    </div>
    <div class="form-group">
     <label class="col-sm-2 control-label">detail</label>
     <div class="col-sm-3">
      @html.textboxfor(x => x.detail, new { @class = "form-control", placeholder = "detail" })
      @html.validationmessagefor(x => x.detail)
     </div>
     <label class="col-sm-2 control-label">second</label>
     <div class="col-sm-3">
      <input class="form-control" type="text" placeholder="" />
     </div>
     <div class="col-sm-2">
      <input class="form-control" type="text" placeholder="weight" />
     </div>
    </div>
    <div class="form-group">
     <label class="col-sm-2 control-label">size</label>
     <div class="col-sm-3">
      @html.textboxfor(x => x.size, new { @class = "form-control", placeholder = "size" })
     </div>
     <label class="col-sm-2 control-label">third</label>
     <div class="col-sm-3">
      <input class="form-control" type="text" placeholder="" />
     </div>
     <div class="col-sm-2">
      <input class="form-control" type="text" placeholder="weight" />
     </div>
    </div>
    <div class="form-group">
     <label class="col-sm-2 control-label">wbs code</label>
     <div class="col-sm-3">
      @html.textboxfor(x => x.wbsnumber, new { @class = "form-control", placeholder = "wbs code" })
     </div>
     <label class="col-sm-2 control-label">fourth</label>
     <div class="col-sm-3">
      <input class="form-control" type="text" placeholder="" />
     </div>
     <div class="col-sm-2">
      <input class="form-control" type="text" placeholder="weight" />
     </div>
    </div>
    <div class="form-group">
     <label class="col-sm-2 control-label">room</label>
     <div class="col-sm-3">
      @html.dropdownlistfor(x => x.roomid,
           (viewbag.rooms as list<selectlistitem>),
           new { @class = "form-control" })
     </div>
     <label class="col-sm-2 control-label">a variance</label>
     <div class="col-sm-3">
      <input class="form-control" type="text" placeholder="a variance" />
     </div>
    </div>
    <div class="form-group">
     <label class="col-sm-2 control-label">area</label>
     <div class="col-sm-3">
      @html.dropdownlistfor(x => x.areaid,
           (viewbag.areas as list<selectlistitem>),
           new { @class = "form-control" })
     </div>
     <label class="col-sm-2 control-label">b variance</label>
     <div class="col-sm-3">
      <input class="form-control" type="text" placeholder="b variance" />
     </div>
    </div>
    <div class="form-group">
     <label class="col-sm-2 control-label">comments</label>
     <div class="col-sm-10">
      <textarea class="form-control" rows="4"></textarea>
     </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="external nofollow" rel="stylesheet" type="text/css" />
 <link href="~/content/libs/fa/css/font-awesome.min.css" rel="external nofollow" rel="stylesheet" type="text/css" /> 
 <link href="~/content/app/css/site.css" rel="external nofollow" rel="stylesheet" type="text/css" />
 <link href="~/content/app/css/bootstrap-extend.css" rel="external nofollow" rel="stylesheet" type="text/css" />
 <link href="~/content/app/css/bootstrap-override.css" rel="external nofollow" 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();
   }
  }

以上这篇asp.net mvc下ajax.beginform方式无刷新提交表单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。