Crafting Code by David Negron

5Jul/090

ASP.NET Cross Page Form Post Using PostBackUrl

Problem:

Recently I worked on a project that required me to provide support for a legacy CGI based form. The main objective of my project was to create an ASP.NET Web Form that would perform a double form post. The first to an internal system and the second to the legacy form. But for the sake of brevity I will only be focusing on how the form post to the legacy form was handled as well as how we went about incorporating client side validation using JavaScript.

Solution:

After some research it turned out that the solution was quite simple. A new button property introduced in .NET Framework 2.0 named PostBackUrl provided me with the required ability to alter form action attribute. Handling the form validation on the other hand proved to be a bit confusing. I knew from working on previous projects that the OnClientClick would be where I would set the JavaScript function call, but I kept running into the situation where the form would fail to complete the post to the legacy form.

After several attempts and some google searches I came across a this post in the ASP.NET forums in which joteke suggested to place ="if(!confirm('OK?'))return false;" inside the OnClientClick property. My original attempt was to simply return the result from the execution of the IsValid() function but apparently I was misunderstanding how the function call would get executed. Modifying the function call as recommended in the ASP.NET forum post yielded the desired behavior I was looking for.

Code:

SampleForm.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SampleForm.aspx.cs" Inherits="Demo.SampleForm" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <title>Sample Form</title>
     <script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
     <script type="text/javascript">
          function IsValid(){
               var txtNameValue = jQuery.trim($('#<%= txtName.ClientID %>').val());
               if(txtNameValue.length == 0){
                    return false;
               }
               else{
                    return true;
               }
          }
     </script>
</head>
<body>
     <form id="frmMain" runat="server">
          <asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
          <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="if(!IsValid())return false;" PostBackUrl="http://www.craftingcode.net" />
     </form>
</body>
</html>
Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • email
  • PDF
  • Reddit
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.