asp.net表单提交时防重复提交并执行前台的JS验证

  在项目开发中,遇到这样的一个情况,就是用户重复提交。当然这个不能怪用户,只能怪.NET或者服务器反应迟钝......我是这样理解的。

  在网上搜了一下,解决方案是不少,比如:

  http://bbs.csdn.net/topics/340048988

  (这个大家提了不少建议)

  http://www.cnblogs.com/blsong/archive/2009/12/24/1631144.html

  (这个基本上总结了网上的方法)

  但实际上做互联网web项目中,需要在前台执行JS或者Jquery的验证(主要是增强用户体验),那么再使用上面的方法,就会出现问题。要么重复提交依然存在,要么前台JS验证失效。最后没办法,只有自己写一个,在满足阻止用户重复提交的情况下,还能保证前台JS验证有效。代码如下:

  

复制代码 代码如下:

  //按钮注册加载样式事件

  var ItSelfButton;

  var ControlRegPostResult = true;

  function AddInputClick() {

  $("input[type='submit']").click(function () {

  ItSelfButton = $(this);

  if (ItSelfButton.attr("repeat") == null) {

  var btnDiv = $("<div>");

  btnDiv.attr("id", "Mask_BTN");

  var divimg = $("<img>");

  divimg.attr("alt", "加载中...");

  divimg.attr("src", "/Images/ButtonLoading.gif");

  divimg.css({ "margin-left": ($(this).width() - 4) / 2, "margin-top": ($(this).height() - 16) / 2 });

  btnDiv.append(divimg);

  btnDiv.css({ width: $(this).width() + 12 + "px", height: $(this).height() + "px", top: $(this).offset().top + "px", left: $(this).offset().left + "px", position: "absolute" });

  $(document.body).append(btnDiv);

  setTimeout(MaskTimeOutRemove, 200);

  }

  });

  }

  $(function () {

  AddInputClick();

  });

  $(window).resize(function () {

  if (ItSelfButton != null) {

  $("#Mask_BTN").css({ top: ItSelfButton.offset().top + "px", left: ItSelfButton.offset().left + "px" });

  }

  });

  function MaskRemove() {

  $("#Mask_BTN").remove();

  }

  function MaskTimeOutRemove() {

  if (!ControlRegPostResult) {

  $("#Mask_BTN").remove();

  ControlRegPostResult = true;

  }

  }

  其中在JS 验证失败中将

  

复制代码 代码如下:

  ControlRegPostResult = false;

  这样基本上满足我的目的了。

  ButtonLoading.gif 可以是一个打转的图片 ,也可以和按钮一样大。反正目的是这个层把按钮遮住。