如何form.onSubmit内致电HTML5 form.checkValidity中的WebForms? [英] How to call HTML5 form.checkValidity during form.onSubmit in WebForms?

查看:810
本文介绍了如何form.onSubmit内致电HTML5 form.checkValidity中的WebForms?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何可以覆盖或扩展,标准的WebForms WebForm_OnSubmit JavaScript函数?

How can i override, or extend, the standard WebForms WebForm_OnSubmit javascript function?

我使用HTML5输入类型在ASP.net的WebForms网站。用户代理(如浏览器,IE,火狐)已经正确地处理数据的消毒,备用UI等。

I am using HTML5 input types in an ASP.net WebForms web-site. The user-agent (e.g. Chrome, IE, Firefox) already correctly handles data sanitization, alternate UI, etc.

通常情况下,当用户点击一个<输入类型=提交> 按钮,用户代理将停止提交,并显示用户界面来指示用户他们的输入将是无效的:

Normally, when a user clicks an <input type="submit"> button, the User-Agent will halt the submit, and show UI to indicate to the user that their input is going to be invalid:

与WebForms的问题是,它不使用的提交的按钮。相反,一切都可以通过一个javascript回发来完成,而不是 提交的形式为:

The problem with WebForms is that it does not use a Submit button. Instead, everything can be done through a javascript postback, rather than submitting the form:

 <asp:LinkButton ID="bbOK" Text="Save User" runat="server" OnClick="bbOK_Click"></asp:LinkButton>

,当渲染到客户端HTML,成为一个对JavaScript的电话:

Which, when rendered into client html, becomes a call to the Javascript:

WebForm_DoPostBackWithOptions(...)

随着很长的形式是一个锚标记:

With the really long form being an Anchor tag:

<a id="Really_Long_Thing_ctl00_bbOK" 
   href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$MainContent$VistaToolbar$ctl00$bbOK", "", true, "", "", false, true))'>
   Save User
</a>

这意味着,用户代理从不给用户一个提示,输入的元素是无效的。

This means that the user-agent never gives the user a prompt that an entered element is invalid.

虽然格式未的提交的,但它仍然触发的onsubmit 事件。我可以使用类似手动触发HTML5表单验证:

Even though the form is not being "submitted", it does still trigger an onsubmit event. I can manually trigger the HTML5 form validation using something like:

isValid = form.checkValidity();

理想我想挂钩的事件在我ASP.web的WebForms网站:

Ideally i would hook that event in my ASP.web WebForms site:

Site.master母

<form runat="server" onsubmit="return CheckFormValidation(this)">

<script type="text/javascript">
   function CheckFormValidation(sender) 
   {
      //Is the html5 form validation method supported?
      if (sender.checkValidity)
         return sender.checkValidity();

      //If the form doesn't support validation, then we just assume true
      return true;
   }
</script>

除在基础设施的WebForms删除 的onsubmit 方法处理程序,并有自己的替换它:

Except that the WebForms infrastructure deletes my onsubmit method handler, and replaces it with its own:

<form id="ctl01" onsubmit="javascript:return WebForm_OnSubmit();" action="UserProperties.aspx?userGuid=00112233-5544-4666-7777-8899aabbccdd" method="post">

所以我自己提交调用将被忽略。看来,钻研 WebForm_OnSubmit 导致下来ASP.net的WebForms验证基础架构的一个兔子洞:

So my own submit call is ignored. It appears that delving into WebForm_OnSubmit leads down a rabbit hole of ASP.net WebForms validation infrastructure:

function WebForm_OnSubmit() 
{
   if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) 
      return false;
   return true;
}

它调用函数:

var Page_ValidationActive = false;
function ValidatorOnSubmit() 
{
    if (Page_ValidationActive) {
        return ValidatorCommonOnSubmit();
    }
    else 
    {
        return true;
    }
}

它调用,调用,使用,检查。

which calls, which calls, which uses, which checks.

问题是WebForms的有 巨大 infrastrucure通过一个标准化的机制在提交前检查表,并显示错误信息给用户(以及整个基础设施,我不使用)。它接管的形式的onsubmit 事件,它没有(不一定)使用&LT;输入类型=提交&GT; 在这个过程中。

The issue is that WebForms has a huge infrastrucure for checking a form before submitting, and displaying errors to users through a standardized mechanism (and entire infrastructure that i do not use). It takes over the onsubmit event of forms, and it doesn't (necessarily) use an <input type="submit"> in the process.

我能做些什么来说服ASP.net WebForms的网站,让用户代理验证表单?

What can i do to convince ASP.net WebForms web-site to let the User-Agent validate the form?

  • HTML5 validation and ASP.net Webforms
  • How do I get Client-side validation of ASP.Net page to run?
  • Trigger standard HTML5 validation (form) without using submit button?
  • MSDN Magazine: Better Web Forms with HTML5 Forms

推荐答案

Web窗体Infrastructure删除处理程序,因为您尝试直接在可视化设计环境添加的元素,和网络的形式没有被设计来解决这个方式。

The web forms infrastructure deletes the handler because you attempt to add it directly on the element in the visual design environment, and web-forms is not designed to work this way.

圈住上提交处理程序很简单,你只需要进行创造性的思考一点。

Trapping the on-submit handler is easy, you just need to think a little creatively.

每当你的设法应付在Web表单环境,这样的事,你要学会思考,经过网页表单页面渲染管线来的解决方案。如果你试图找到直接的工作网络形式的发动机内部​​的解决方案,那么网络的形式将赢得每一次。

Whenever your trying to deal with anything like this in a web-forms environment, you have to learn to think about solutions that come after the web-forms page rendering pipeline. If you try to find a solution that works directly inside the web-forms engine, then web-forms will win every-time.

您可以在这里重现我的精确检验情况下,如果你需要太多,或者可以根据需要挑选出您所需要的比特和再利用。

You can reproduce my exact test case here if you need too, or you can pick out the bits you need and re-use as required.

C#创建一个新的Web表单项目(你可以做到这一点在VB中,如果你想要的,但我把我的例子为C#),一旦你的项目已经创建,用鼠标右键单击您的应用程序引用,进入的NuGet安装JQuery的。

Create a NEW web-forms project in C# (You can do it in VB if you want, but I'm putting my examples as C#), once your project has been created, right click on your application references, go into NuGet and install JQuery.

这是可能的了jQuery来做到这一点,只使用本地方法,但它是星期天,我正在懒洋洋的今天: - )

It is possible to do this with out JQuery, and just use native methods, but it's Sunday and I'm being lazy today :-)

一个新的网络形式添加到您的项目(使用添加新项),并称之为'的 Default.aspx的的',到这个表单中添加一些文字,一个文本框按钮和标签。

Add a new web-form to your project (using add new item) and call this 'Default.aspx', onto this form add some text, a text box a button and a label.

您的code应该类似于:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="jsvalidation.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    Please enter your name :
    <asp:TextBox ID="txtName" runat="server" data-jsname="username"></asp:TextBox>
    <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit"     />
  </div>
  <asp:Label runat="server" ID="lblResult">...</asp:Label>
  </form>

</body>
</html>

然后preSS F7(或按钮双击)去后面的编辑为您的表单的code。

Then press F7 (or double click on the button) to go to the code behind editor for your form.

添加您的code的按钮处理程序到您的code后面。如果你做的事情完全一样的我,您code应类似于此:

Add your code for the button handler into your code behind. If your doing things exactly the same way as me, your code should look similar to this:

using System;

namespace jsvalidation
{
  public partial class Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {}

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
      if(Page.IsPostBack)
      {
        lblResult.Text = "Well hello there " + txtName.Text;
      }
    }
  }
}

在这一点上,你可以测试的东西通过pressing F5工作,你输入什么都(或不输入)在文本框中,应该在下面的标签,当你preSS消息出现提交按钮。

At this point you can test things work by pressing F5, and what ever you enter (or don't enter) in the text box, should appear with the message in the label below when you press the submit button.

现在我们已经建立了一个基本的web表单,我们只需要拦截的形式提交。

Now we have a basic web-forms set up, we just need to intercept the form submit.

正如我刚才所说,你需要考虑在网络表单框外。

As I said a moment ago, you need to think outside the web-forms box.

这意味着你需要运行截取后的页面已经被渲染和发送到浏览器。

That means you need to run your intercept AFTER the page has been rendered and sent to the browser.

所有JS所允许的页面输出前进行网络的形式注入到混合通常执行,开幕body标签之前,这意味着,中

All of the JS that web-forms injects into the mix is usually executed before the page output is allowed to proceed, which means before the opening body tag.

为了让您的code后运行,你需要把你的脚本在HTML输出的 END ,以便它跑最后一棒。

In order to get your code to run after it, you need to put your script at the END of the html output so that it runs last.

添加以下code刚刚结束标记之前,但在收盘表单标签

<script src="/Scripts/jquery-2.1.1.js"></script>
<script type="text/javascript">

  $(document).ready(function() {

    $('form').submit(function() {

      var uninput = $('input[data-jsname="username"]');
      var username = uninput.val();

      if (username == "")
      {
        alert("Please supply a username!");
        return false;
      }

    });

  });

</script>

您之间的高一筹,将马上,我不是调用HTML5验证API注意,原因是我试图保持这个例子简单。

The more astute among you, will notice straight away that I'm not calling the HTML5 validation API, the reason is I'm trying to keep this example simple.

我在哪里检查用户名值是重要的组成部分。

Where I check the username value is the important part.

所有的事情就是我在其中执行检查返回true或false匿名函数。 (真正的是,如果你不返回任何默认)

All that matters is the anonymous function in which I perform the check returns true or false. (True is the default if you DON't return anything)

如果您返回一个错误,你会prevent后回发生,从而使您到c你需要使用HTML5 API验证表单字段更改使用任何JS $ C $。

If you return a false, you'll prevent the post back taking place, thus allowing you to use whatever JS code you need to make the form fields change using the HTML5 validation API.

我个人的preference就是用引导(见syncfusion免费的电子图书范围为我的引导2本书,即将发布的引导3册),在那里你可以在框架中使用特殊标记和CSS类如有-错误颜色适当的事情。

My personal preference is to use bootstrap (See the syncfusion free e-book range for my Bootstrap 2 book, and soon to be released Bootstrap 3 book), where you can use special markup and css classes in the framework such as "has-errors" to colour things appropriately.

至于使用JQuery组件的选择,以及有这里的两件事情你需要注意了。

As for the selection of the components using JQuery, well there's 2 things here you need to pay attention too.


  • 1),你永远不应该有一个web的表单页面上不止一种形式,其实如果我没有记错,如果你做你的应用程序将无法编译,或者顶多就一定会抛出一个除了在运行时。

  • 1) You should NEVER have more than one form on a web-forms page, in fact if I remember correctly, your app will fail to compile if you do, or at the most it'll certainly throw an exception at run-time.

2)怎么一回事,因为你永远只能有一种形式,那么你可以在使asumption非常安全,在JQuery的一个通用的形式选择器将只选择您的主要形式(不考虑ID,姓名,或缺乏其大小),并添加onsubmit处理它,总是会附上这个网络形式已don'e它的事情。

2) Beacuse you only ever have one form, then you can be very safe in making the asumption, that a generic 'form' selector in JQuery will only ever select your main form (Irrespective of the ID, name, lack or size thereof) and adding an onsubmit handler to it, will always attach this after web-forms has don'e it's thing.

3)怎么一回事,因为网络的形式可以(并且通常)轧ID名称,它通常更易于使用数据属性自定义位添加到您的标签。实际的ASP.NET JS端验证这是否完全相同的伎俩本身,让JS code和.NET code愉快地共存于同一页面。有办法告诉.NET如何命名编号的,但通常你必须设置很多的地方很多的选择,而且它很容易错过一个。使用数据属性'和JQ属性选择语法实现同样的事情的一个更加安全,更易于管理的方式。

3) Beacuse web-forms can (and usually does) mangle ID names, it's generally easier to use 'data attributes' to add custom bits to your tags. The actual ASP.NET js side validation does this exact same trick itself to allow JS code and .NET code to happily co-exist in the same page. There are ways to tell .NET how to name the ID's but generally you have to set lots of options in lot's of places, and it's very easy to miss one. Using 'data attributes' and the JQ attribute selector syntax is a much safer, easier to manage way of achieving the same thing.

这不是一个困难的任务,但我不得不承认,这不是一个是显而易见的,如果你的不是找围栏外的网络的形式建立在你身边。

It's not a difficult task, but I have to admit, it's not one that's immediately obvious if your not looking outside the fence that web-forms builds around you.

Web的形式是专为快速应用程序开发,主要用于用于桌面双赢的形式模型开发者。虽然网络形式仍然有它的地位,这些天,新的绿地的应用程序,我会建议寻找其他选项的一点,就是建立在新的HTML5规范正在努力躺下,并得到正确的基础ESP的。

Web-forms is designed for rapid application development, primarily for devs used to the desktop win-forms model. While web-forms still has it's place these days, for new greenfield apps I would recommend looking at other options too, esp ones that build on the foundations that the new HTML5 specifications are trying hard to lay down and get right.

这篇关于如何form.onSubmit内致电HTML5 form.checkValidity中的WebForms?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆