Saturday, July 6, 2013

CSharp c# ASP.NET web page simple example with form and postback

CSharp c# ASP.NET web page simple example with form and postback

Overview:
The example below is focused on using the IsPostback value but to do this you need to run a asp:button in the aspx page, as opposed to response.write the html.  If you want to just use response.write html then by-pass the  value IsPostback and just check for expected values.  Note, however, that "Request.Form.GetValues("tom")[0]" will only get the control by the "name" attribute, instead of the "id" attribute of the input cell.



c:\CLKTest4\WebForm1.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" EnableViewState="false" Inherits="CLKTest4.CLKTest" %>

<html>
   <head>
       <title>This is my title</title>
   </head>
   <body>
       <br/>
       <form id="clkform" PostBackUrl="WebForm1.aspx" method="post" runat="server">
           <input id="tom" type="text" runat="server" />
           <asp:Button ID="Button1" text="Submit" runat="server" />
       </form><br/>
       </body>
   </html>




c:\CLKTest4\WebForm1.aspx.cs:

using System;



namespace CLKTest4
{
   public partial class CLKTest : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {
     
           string tomNow = "nothing";
           try
           {
               tomNow = Request.Form.GetValues("tom")[0];
           }
           catch
           {
               Response.Write("<br/>");
               Response.Write("tomNow exception");
               Response.Write("<br/>");
           }



           Response.Write("<br/>");
           Response.Write("tomNow=" + tomNow);
           Response.Write("<br/>");

        
           if (IsPostBack)
           {
               Response.Write("<br/>");
               Response.Write("This is a postback");
               Response.Write("<br/>");
           }
           else
           {               
               Response.Write("<br/>");
               Response.Write("This is not a postback - it is a fresh call to this page");
               Response.Write("<br/>");
           }
   
       }
   }

}


No comments:

Post a Comment