如何在 WebForms 中的 form.onSubmit 期间调用 HTML5 form.checkValidity? [英] How to call HTML5 form.checkValidity during form.onSubmit in WebForms?

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

问题描述

如何覆盖或扩展标准的 WebForms WebForm_OnSubmit javascript 函数?

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

我在 ASP.net WebForms 网站中使用 HTML5 输入类型.用户代理(例如 Chrome、IE、Firefox)已经正确处理数据清理、替代 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.

通常,当用户点击 按钮时,User-Agent 将停止提交,并显示 UI 以向用户表明他们的输入是将无效:

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.

即使 form 没有被提交",它仍然会触发一个 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 基础结构删除了 my 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 有一个巨大 基础设施,用于在提交前检查表单,并通过标准化机制(以及我不知道的整个基础设施)向用户显示错误利用).它接管了表单的 onsubmit 事件,并且它不会(必须)在过程中使用 .

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?

推荐答案

Web 表单基础结构删除了处理程序,因为您尝试将其直接添加到可视化设计环境中的元素上,而 Web 表单并非旨在处理此问题方式.

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 表单环境中处理此类问题时,您都必须学会考虑在 Web 表单页面呈现管道之后出现的解决方案.如果您尝试找到直接在 Web 表单引擎中工作的解决方案,那么 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.

您的代码应该类似于:

<%@ 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>

<asp:Label runat="server" ID="lblResult">...</asp:Label></表单>

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

然后按 F7(或双击按钮)转到表单的代码隐藏编辑器.

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; } } } }

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.

此时您可以通过按 F5 来测试工作是否正常,并且您在文本框中输入(或不输入)的任何内容都应该在您按下提交按钮时显示在下面的标签中.

现在我们有一个基本的网络表单设置,我们只需要拦截表单提交.

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.

web-forms 注入到 mix 中的所有 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.

为了让您的代码在它之后运行,您需要将脚本放在 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.

在结束正文标记之前添加以下代码,但在结束表单标记之后

<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)

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)

如果您返回 false,您将阻止回发,从而允许您使用任何您需要的 JS 代码来使用 HTML5 验证 API 更改表单字段.

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.

我个人更喜欢使用 bootstrap(请参阅我的 Bootstrap 2 书籍的同步融合免费电子书系列,以及即将发布的 Bootstrap 3 书籍),您可以在其中使用框架中的特殊标记和 css 类,例如"has-errors"以适当地给事物着色.

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) 一个网页表单上的表单永远不应该超过一个,事实上,如果我没记错的话,如果你这样做,你的应用程序将无法编译,或者最多肯定会抛出一个运行时异常.

  • 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) 因为你只有一个表单,所以你可以非常安全地做出假设,即 JQuery 中的通用表单"选择器只会选择你的主表单(无论 ID、名称如何),缺少或大小)并向其添加提交处理程序,将始终附加此之后网络表单完成它的事情.

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 代码和 .NET 代码在同一页面中愉快地共存.有很多方法可以告诉 .NET 如何命名 ID,但通常你必须在很多地方设置很多选项,很容易错过一个.使用数据属性"和 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-forms 专为快速应用程序开发而设计,主要面向习惯于桌面 win-forms 模型的开发人员.虽然 Web 表单如今仍然占有一席之地,但对于新的未开发应用程序,我建议您也查看其他选项,尤其是建立在新 HTML5 规范努力制定和正确的基础上的选项.

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.

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

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