How to call HTML5 form.checkValidity during form.onSubmit in WebForms?

主宰稳场 提交于 2019-12-04 08:33:25

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.

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.

Step 1

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.

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

Step 2

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.

your code should look similar to:

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

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

Step 3

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.

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

Step 4

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.

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.

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.

add the following code just before the closing body tag, but AFTER the closing form tag

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

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.

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)

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.

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.

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

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

Summary

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!