Home
Links
Home Page
HTML_AJAX In operation
The guidebook on an exchange of links
Bases of creation of server elements of management. Events
Postback and Query String - to combine incompatible
Kategorial`noe ordering of results of search
We change URL'? hurriedly
XML+MSSQL+ASP.NET. A part 1.
As work Web services ASP.NET
New in ASP.NET 2. Structures of users
Transformation of a target stream of the XML-given at a conclusion in a browser means ASP.NET and XS
Expectation of performance of long process in ASP.NET
Difference between HttpModule and HttpHandler
New in asp.net 2 - subjects and skiny.
Review GridView
What is GridView
Role of a content in promotion of a site
Review DetailsView
Job with databases
AutoPostBack Binding to the data. Collections. Check of correctness of the entered data

. AutoPostBack Binding to the data. Collections. Check of correctness of the entered data.

Property AutoPostBack


Programming in ASP.NET is focused on events. Events on page, for example, pressing the button, are processed on the server. Changes in the text of a field of editing, a choice of an option in the list, pressing a tag or the switch do not cause immediate sending on the server. It can be achieved if to establish property AutoPostBack for these elements.


If AutoPostBack it is established for an element of management TextBox for him{it} event TextChanged as soon as the field will lose focus will be caused or key Enter will be pressed. That this property worked, the browser should support ECMAScript (standard JavaScript accepted by the European association of manufacturers of computers).


As source of the data for elements of management tables of the data can serve. Let's disassemble an example included Visual Studio - CarSelectorSample. Business occurs in electronic shop of automobiles. There are different stamps of machines, and for each stamp there are some models. At a choice of the stamp of the machine in the first list in the second list automatically gruzjatsja corresponding models.


Brand Buick Chevrolet Pontiac Toyota Mileage Features

Power seat

Buick Century Impala Grand Am Avalon 0-10000 Leather seat

Chevrolet LeSabre Malibu Grand Prix Camry 10000-20000 Sun roof

Pontiac Park Avenue Metro Montana Camry Solara 20000-30000 CDs player

Toyota Regal Prizm Sunfire Celica 30000 and more ABS


All data used on this page, are collected in the table. For storage of such table there is class DataTable. The table will consist from stolbcov - DataColumn and lines DataRow. Class DataView allows to create various data presentations of the table. The first column is a source of the data of the list of stamps. Depending on the chosen model one of 2-5 columns is loaded into the list of models.


In the beginning the table is created



Cars = new DataTable ();

  Cars. Columns. Add (new DataColumn ("Brand", typeof (string)));


Here one of designers DataColumn is caused. The first argument - the name of the column, the second - type.



CarRow = Cars. NewRow ();


The new line of the table is created. The cell of the table is set with the help of an index of a line.



CarRow [6] = " Power seat ";


And the line is added in the table.



Cars. Rows. Add (CarRow);


At the dropping out list of stamps property AutoPostBack is established. It means, that the page automatically moves on the server when in it of the list the chosen element varies.


In obrabotchike a choice of a new element in the beginning it is found out, what element is chosen.



string selected = DropDownList1. SelectedItem. Value;


In the operator switch there is a switching the second list on one of stolbcov tables the task of properties DataTextField and DataValueField, where DataTextField - the text displayed in the list, and DataValueField - the chosen value. In this case, as often it happens, they are identical.



Binding to the data


Some elements of management: lists, tables and others - have property DataSource which is responsible for binding to the data. The type of this property - object, that is can be any type, but this type should realize interface IEnumerable. Often values of this property appoint collections. In that case there is no need to add values manually. Property DataSource can be adhered to the collections supporting interfaces IEnumerable, ICollection or IListSource. A source of the data also can be XML-files, databases. A call of method DataBind the data become attached to an element of management. Method Page. DataBind causes binding the data in all elements on page.


The resulted below dropping out list helps to choose continent for travel. A source of the data - dynamic file ArrayList. Use it{him} if in the program there are many inserts and removals{distances}.



void Page_Load ()

      {

          ArrayList ContinentArrayList = new ArrayList ();

          ContinentArrayList. Add ("Worldwide");

          ContinentArrayList. Add ("America");

          ContinentArrayList. Add ("Africa");

          ContinentArrayList. Insert (1, "Asia-Pacific");

          ContinentDropDownList. DataSource = ContinentArrayList;

          ContinentDropDownList. DataBind ();

} // End Page_Load ()

  ....

  <asp:DropDownList id = "ContinentDropDownList" runat = "server"/>


It is possible to use as a source of the data of the khesh-table (Hashtable). KHesh-tables are structures of the data which have been thought up for a long time (see 3 that of " Art of programming » D.Knuta), but programmers long time have been compelled to realize them manually. In language php the usual file also is the khehsh-table. In library STL for language With ++ too there is a type map in which the data are stored{kept} in such a way. KHesh-tables allow to find very quickly value on a key. The index in a collection is calculated as simple khehsh-function of a key. In C * keys are used as indeksatory. Use Hashtable if in the program search often is carried out. The insert and removal{distance} occur in him slowly. Keys can be any type. In class Object virtual method GetHashCode is determined, he and is used in Hashtable.



<% Page Language = " C * " %>

  <! DOCTYPE html PUBLIC " - // W3C // DTD XHTML 1.0 Transitional // EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <script runat = "server">

  void calSelectChange (Object sender, EventArgs e)

  {

       lblShow. Visible = false;

       Hashtable hshDays = new Hashtable ();

       hshDays [Convert. ToDateTime ("2/6/2006")] = " Examination on algebra ";

       hshDays [Convert. ToDateTime ("3/6/2006")] = " Examination on With * ";

       hshDays [Convert. ToDateTime ("4/6/2006")] = " the Beginning of studying of a rate ASP.NET ";

       hshDays [Convert. ToDateTime ("1/6/2006")] = " Day of protection of children ";

       DateTime datDateIn;

       datDateIn = calDays. SelectedDate;

       if (Page. IsPostBack)

       {

           lblShow. Text = " this day it is appointed: ";

           lblShow. Text + = hshDays [datDateIn];

           if (hshDays [datDateIn] == null)

               lblShow. Text = " it is appointed nothing ";

           lblShow. Visible = true;

}

}

  </script>

  <html xmlns = " http: // www.w3.org/1999/xhtml ">

  <head runat = "server">

      <title> we Shall try the khehsh-table </title>

  </head>

  <body>

      <form id = "form1" runat = "server">

      <div>

      <h3> the Daily log

  </h3>

  Enter date between 1/6/2006 and 30/6/2006

  <asp:Calendar id = "calDays" runat = "server" 

  OnSelectionChanged = "calSelectChange"

  VisibleDate = "06/06/2006"

> </asp:Calendar>

  <br/>

  <br/>

  <asp:Label id = "lblShow" runat = "server"> </asp:Label>

      </div>

      </form>

  </body>

  </html>


Here a key of the khehsh-table is date. Convert. ToDateTime converts a line in type of date. VisibleDate guarantees, that on a calendar there will be a June, 2006. If values on a key in the table no, indeksator simply returns null. Values can be entered in any order.


It would be desirable to add a new opportunity of introduction of new recordings in page. It is possible to enter new elements of management - a line of input and the button for submission of the data. At processing pressing the button we shall add in the khehsh-table new value.



void Button1_Click (object sender, EventArgs e)

      {

          hshDays [calDays. SelectedDate] =TextBox1. Text;

}


This page does not work. The matter is that the page is loaded anew when date varies. The KHehsh-table is created anew, and the values entered into it{her} are lost. How to solve this problem? We shall make the khehsh-table of a static variable.



static Hashtable hshDays;

  void calSelectChange (Object sender, EventArgs e)

  {

      DateTime datDateIn = calDays. SelectedDate;

      lblShow. Text = " this day it is appointed: ";

      lblShow. Text + = hshDays [datDateIn];

      if (hshDays [datDateIn] == " ")

          lblShow. Text = " it is appointed nothing ";

}

  void Page_Init ()

  {

      if (! Page. IsPostBack)

      {

          hshDays=new Hashtable ();

          hshDays [Convert. ToDateTime ("2/6/2006")] = " Examination on algebra ";

          hshDays [Convert. ToDateTime ("3/6/2006")] = " Examination on With * ";

          hshDays [Convert. ToDateTime ("4/6/2006")] = " the Beginning of studying of a rate ASP.NET ";

          hshDays [Convert. ToDateTime ("1/6/2006")] = " Day of protection of children ";

          Session ["Diary"] = hshDays;

}

}

  void Record (Object sender, EventArgs e)

  {

      DateTime datDateIn = calDays. SelectedDate;

      hshDays [datDateIn] = Entrance. Text;

      lblShow. Text = hshDays [datDateIn] .ToString ();

}



Classes of check of given{data} (Validatory)


The data from forms usually enter the name in databases, and the type of the information in them should correspond{meet} to type and length of the tables of databases given in fields. Besides sometimes it is necessary to enter the interconnected data, for example the password during registration it is necessary to enter 2 times, and he in both fields should coincide. Some hackers try to enter program codes into forms to crack your system. Vigilance and more time vigilance as comrade spoke... I do not remember who. And if the user has entered the incorrect data casually, the server will give out not clear message on a mistake, and the valuable client will leave from our site on another.


Before to work with the data, it is necessary to be convinced, that:


* The information is entered into the certain field;

* The text in a field the address has the form of the electronic address (with and with a point);

* Date of a birth is reasonable, for example, the user did not inform about itself, that to him 300 years or 1 godik.

* The password is combined enough and does not coincide with a login.


Check can occur and on the party{side} of the client, and on the server. At validacii on the party{side} of the client in page the code on Javascript is built. If the data in the form do not pass check, the page simply will not be sent on the server. Thus we shall avoid the superfluous traffic and we shall not load the server. On the other hand, validacii on the party{side} of the server is more reliable. A Javascript-code hackers can easily see and send the wrong data which will pass this check. At last, Javascript it is possible to switch off simply in adjustments of a browser. At validacii on the party{side} of the server the data are checked by the program in high-grade language. Its{her} code to the user is unknown. As a result of check the new page with error messages is generated. The most reasonable strategy - to apply a combination of these methods. Preliminary check at the client will protect from typing errors, and serious check on the server - from ill-intentioned breaking.


There is a lot of server elements of management which are not engaged in a conclusion of the information, and check the data entered by the user. ASP.NET 2.0 itself defines{determines} type of a browser and generates the code most suitable to the given case, which. If the browser supports a Javascript-code which he can send validacija or its{her} part occurs on the party{side} of the client. If the browser does not support Javascript all validacija occurs on the server.


To get access to validatoram it is simple - open in Toolbox tab Validation.


Klasy validatorov form hierarchy in which chapter{head} there is abstract class BaseValidator.


Base class validatorov the successor of class Label so in essence all validatory - labels, the text in which becomes seen when conditions of check are not carried out opredelennnye us. By default the text in validatorakh red. (Recollect school and remarks to the teacher in a writing-book). But certainly, this color to change for more pleasant. All validatory have property ControlToValidate. It sets that kontrol, the data in which are checked by the data validatorom. This element should be in one container with validatorom.

The general{common} properties validatorov

Whether Display To give a place statically or dynamically

Whether EnableClientScript To allow to generate a client code

ErrorMessage the Text of the message on a mistake

Whether IsValid Has passed validaciju connected with validatorom an element

Iniciacija checks of the data


Check is always initiated by any event. Usually it is click on buttons Button, ImageButton, LinkButton in which by default property CausesValidation is established in true. It is possible to clean{remove} this property for some buttons for which it is not necessary, for example, buttons Cancel.


In an example with a motor show on page are available a little validatorov.



<asp:requiredfieldvalidator id = "RequiredFieldValidator2" runat = "server" 

                          ErrorMessage = "Required" 

                          ControlToValidate = "DropDownList1">

                                                 </asp:requiredfieldvalidator>


Class RequiredFieldValidator checks, whether value in the element of management connected to it{him} has been changed. If, as in this case, it is the dropping out list, empty value is originally chosen, but it is required, that the user has chosen the concrete stamp. If not has chosen, but has pressed the button submit, validacija the text set in ErrorMessage or in Text fails and deduced. Validatory display the text specified in property "Text", always, when it is not empty, and the text established in property "ErrorMessage" when property "Text" is equal " ". Initial value is set by property InitialValue. If this property is not set, check is spent on absence of value (for example, empty Textbox).


For check of a correctness of input of the electronic address class RegularExpressionValidator is used.



<span class = "label"> Your Email </span> <span class = "label1"> *nbsp; (Required) </span> *nbsp;

  <asp:textbox id = "TextBox1" runat = "server"> </asp:textbox> *nbsp;

  <asp:RegularExpressionValidator id = "RegularExpressionValidator1" runat = "server" ControlToValidate = "TextBox1" ErrorMessage = " Not a valid Email " ValidationExpression = " w + ([-+.] w +) * w + ([-.] w +)*.w + ([-.] w +) * "> </asp:RegularExpressionValidator>

  <asp:RequiredFieldValidator id = "RequiredFieldValidator1" runat = "server" ControlToValidate = "TextBox1" ErrorMessage = "*"> </asp:RequiredFieldValidator>

  </span>


ValidationExpression - regular expression, on conformity to which passes check value of a text field. In Visual Studio 2005 gives some ready patterns of regular expressions which can be chosen in a property sheet - telephone numbers{rooms} of the different countries, addresses, and, the most useful, patterns of email and the Internet Address.


To one element of management can be connected a little validatorov. For example, the electronic address is checked and on conformity to a pattern, and on obligatory filling.


Property Page. IsValid allows to define{determine}, whether all page validaciju has passed. For browsers which support DHTML, check occurs on the party{side} of the client. For this purpose the JavaScript-code is automatically generated. Thus resources of the server and the traffic which should be spent for transfer of the wrong data are saved.



Validatory comparisons


CompareValidator compares value to value in the other element of management or with a constant. Also it is possible to check up, whether it is possible to convert value in the element of management connected to it{him} in any type.


Property Operator allows to establish operation by means of which there is a comparison: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual. Value DataTypeCheck means check on conformity to type.


Property Type can accept values String, integer, Date, Double and Currency.


Property ControlToCompare sets an element of management to which there is a comparison. ValueToCompare sets value. From these two properties one can be established only.


RangeValidator checks conformity of the entered value to a range set svostvami MinValue and MaxValue.



<asp:TextBox ID = "TextBox1" runat = "server"> </asp:TextBox>

  <asp:RangeValidator ID = "RangeValidator1" runat = "server" 

      ControlToValidate = "TextBox1"

      ErrorMessage = " there are more 10 bottles of beer per customer " 

      MaximumValue = "10" MinimumValue = "1" Type = "Integer">

  </asp:RangeValidator>


ValidationSummary


Class ValidationSummary allows to deduce{remove} the final information on all validatoram on page. She can be deduced{removed} in the various form:


* BulletList - the list with badges

* List - the usual list

* SingleParagraph - the simple paragraph


The information can be deduced{removed} on page, and it is possible in an information window if ShowMessage to put in True. For all validatorov property Error Message, instead of the text is deduced. Text it is deduced in itself validatore.


Let's return to page Registration.aspx. We shall add in him{it} one more field for input of the password.



<form runat = "server" id = "input">

      <asp:Label ID = "Label1" runat = "server" Text = " Enter a name: " Width = "140px"> </asp:Label>

  <asp:TextBox ID = "txtName" runat = "server" CausesValidation = "True"/>

      <asp:Label ID = "Label2" runat = "server" Text = " Enter the address: " Width = "140px"> </asp:Label>

  <asp:TextBox id = "txtAddress" runat = "server" textmode = "multiline" rows=5

/>

  <br/> <br/>

      <asp:Label ID = "Label3" runat = "server" Text = " Enter the password: " Width = "140px"> </asp:Label>

      <asp:TextBox id = "txtPassword" runat = "server" textmode = "password"/>

      <br/>

  <br/>

      <asp:Label ID = "Label4" runat = "server" Text = " Repeat the password " Width = "140px"> </asp:Label>

      <asp:TextBox id = "TextBox1" runat = "server" textmode = "password"/> <br/>

     <asp:Button ID = "Button1" runat = "server" Text = "Submit"/>

  </form>


Property CausesValidation works, when the element of management loses focus. In that case connected to it{him} validator shows value of property Text.


It is necessary for us, that the name has been necessarily entered, and the password coincided in both text fields.


Drag RequiredFieldValidator and throw it{him} on the form. ControlToValidate establish in txtName. The second validator - RequiredFieldValidator for the password. The third - CompareValidator which compares value of passwords.



<asp:RequiredFieldValidator ID = "RequiredFieldValidator1" ControlToValidate = "txtName"

      Display = "Static" ErrorMessage = " the Name is necessary for entering " runat = "server"> * </asp:RequiredFieldValidator>

          <asp:RequiredFieldValidator ID = "RequiredFieldValidator2" runat = "server" ErrorMessage = " the Password should not be empty " ControlToValidate = "txtPassword1"> * </asp:RequiredFieldValidator>

  <asp:CompareValidator ID = "CompareValidator1" runat = "server"

      ControlToValidate = "txtPassword1"

      ErrorMessage = " Passwords should coincide! " ControlToCompare = "txtPassword2"> </asp:CompareValidator> <br/>


And also one ValidationSummary:



<asp:ValidationSummary ID = "ValidationSummary1" runat = "server"/>


Let's put the button, by pressing on which there will be a check.



<asp:Button ID = "Button1" runat = "server" Text = "Validacija" OnClick = "Validate_Click"/>


Obrabotchik pressing the button are confirmed with input if validacija has passed successfully:



protected void Validate_Click (object sender, EventArgs e)

      {

          if (Page. IsValid)

          {

              lblName. Text = " ";

              lblAddress. Text = " ";

              lblPassword. Text = " ";

              input. Visible = false;

              if (txtName. Text! = " ")

                  lblName. Text = " you have entered a name: " + txtName. Text;

              if (txtAddress. Text! = " ")

                  lblAddress. Text = " you have entered the address: " +

              txtAddress. Text;

              if (txtPassword1. Text! = " ")

                  lblPassword. Text = " you have entered the password: " +

                      txtPassword1. Text + " <br> Thanks for registration! ";

}

}


All check of this page occurs at the client. Can even stop the server that in it to be convinced. Only when all data are entered correctly, there is a sending of the form on the server.

CustomValidator


If it is necessary to make such check which cannot be carried out with the help standard validatorov, game enters CustomValidator. In class CustomValidator it is possible to write any function which will check values both on the party{side} of the server, and at the client. A classical example - check of number on parity.


Let's write pol`zovatel`kij validator which will check the password for the length - not less than 5 symbols.



<head>

      <title> Registration of the new user </title>

  <script language = "JavaScript">

  function validatePassword (oSrc, args)

  {

      args. IsValid = (args. Value.length> 5); 

}

  </script>

  </head>

  ......

      <asp:CustomValidator ID = "CustomValidator1" runat = "server" 

          ControlToValidate = "txtPassword1"

          ErrorMessage = " too short password " Display = "Static"

          ClientValidationFunction = "validatePassword"> * </asp:CustomValidator>


Check occurs on the party{side} of the client function on JavaScript validatePassword. For this purpose it is necessary in property ClientValidationFunction to write down a name of function. In the generated code such code is adhered to the button:



<input type = "submit" name = "Button1" value = "Button" onclick = " javascript:WebForm_DoPostBackWithOptions (new WebForm_PostBackOptions (*quot; Button1*quot;, *quot; *quot;, true, *quot; *quot;, *quot; *quot;, false, false)) " id = "Button1"/>


It is known, that if the function connected with onclick, will return logic value false, the form will not be sent on the server.



<asp:CustomValidator ID = "CustomValidator1" runat = "server" 

          ControlToValidate = "txtPassword1"

          ErrorMessage = " too short password " Display = "Static"

          OnServerValidate = "ServerValidate"> * </asp:CustomValidator> <br/>


Let's make same validaciju on the server. To start check on the server, property OnServerValidate is used. Function which is specified in her, is included into a class of page and should be written on C *:



void ServerValidate (object source, ServerValidateEventArgs args)

      {

          string password = args. Value. ToString ();

          int len = password. Length;

          args. IsValid = (len> = 5);

}


ServerValidate it is caused after event Page_Load, therefore it is impossible, as in lecture 3, to deduce{remove} results in Page_Load.


It is possible to spend simultaneously also both client, and server validaciju:



<asp:CustomValidator ID = "CustomValidator1" runat = "server" 

          ControlToValidate = "txtPassword1"

          ErrorMessage = " too short password " Display = "Static"

          OnServerValidate = "ServerValidate" 

          ClientValidationFunction = "validatePassword"> * </asp:CustomValidator>


To disconnect an opportunity of generation of a client code for all validatorov, it is possible to write:



void Page_Load ()

      {

          foreach (BaseValidator bv in Page. Validators)

          {

              bv. EnableClientScript = false;

}

}


For display of the message on a mistake it is possible to use sounds and a picture. For this purpose in property ErrorMessage it is necessary to write down not the text, and corresponding teg HTML, for example:



ErrorMessage = ' <img src = "error.gif"> '


Groups validacii.


Sometimes it happens it is necessary to have some buttons on page, and by pressing everyone the information from logically interconnected groups of elements of management is entered. Therefore values only from this group should be checked. At all validatorov and elements management through which input of the information is possible{probable}, is property ValidationGroup. Function Page. Validate () too can be used with such parameter. If there is a pressing the button with established ValidationGroup, check of those validatorov, at which this property same is started.



The conclusion


Purpose{Appointment} of forms in obtaining the data from users, but the data have no sense if they are entered incorrectly. Elements - validatory allow to automate routine actions on check of the data and to guarantee the data input, corresponding to our requirements.






© Web Development Company Conkurent, LLC 2008-2009. All rights reserved.