Sunday 9 December 2012

Advanced ASP NET Server Controls

Goals:
  • Present advanced ASP.NET server controls (data display controls are not included here).
Steps:
  1. Create a new ASP.NET Web Application project in Visual Studio.
  2. Table
    • The Table control is a useful way to dynamically generate or modify a table. The Table's content can be easily created using the Designer:
    • Content of the table can be dynamically modified also:
      protected void Page_Load(object sender, EventArgs e)
      {
          
      if (!IsPostBack)
          {
              Table1.Rows[1].Cells.RemoveAt(2);
              Table1.Rows[1].Cells[0].HorizontalAlign =
      HorizontalAlign.Center;
              Table1.Rows[1].Cells[0].ColumnSpan = 2;

              
      TableRow tr = new TableRow();
              Table1.Rows.Add(tr);

              
      TableCell tc = new TableCell();
              tc.Text =
      "Seventh";
              tr.Cells.Add(tc);

              tc =
      new TableCell();
              tc.Text =
      "Eight";
              tr.Cells.Add(tc);

              tc =
      new TableCell();
              tc.Text =
      "Ninth";
              tr.Cells.Add(tc);
          }
      }
  3. Calendar
    • It is a quite functional control for presenting a calendar to the user.

      Take a look at the generated HTML code to see how many HTML code is necessary to render the calendar.
      Note, that changing a month causes a postback. Unfortunately, this is a limitation of this control. The user's inconvenience can be reduced using AJAX, but for the most demanding users other Calendar control must be used.
    • Selecting a day causes the SelectionChange event:
      protected void Calendar1_SelectionChanged(object sender, EventArgs e)
      {
          Literal7.Text =
      "Selected day: " + Calendar1.SelectedDate.ToString();
      }
  4. AdRotator
    • This is an interesting control which allows to display advertisements to the page.
    • It is based on an XML file containing data of advertisements. Add to the project a new XML file, named Ads.xml, placed in the App_Data folder. Put the following sample content into this file:
      <?xml version="1.0" encoding="utf-8" ?>
      <
      Advertisements>
          <
      Ad>
              <
      ImageUrl>~/Images/1st.jpg</ImageUrl>
              <
      NavigateUrl>http://www.1st.com</NavigateUrl>
              <
      AlternateText>1st</AlternateText>
              <
      Impressions>10</Impressions>
              <
      Keyword></Keyword>
          </
      Ad>
          <
      Ad>
              <
      ImageUrl>~/Images/2nd.jpg</ImageUrl>
              <
      NavigateUrl>http://www.2nd.com</NavigateUrl>
              <
      AlternateText>2nd</AlternateText>
              <
      Impressions>10</Impressions>
              <
      Keyword></Keyword>
          </
      Ad>
          <
      Ad>
              <
      ImageUrl>~/Images/3rd.jpg</ImageUrl>
              <
      NavigateUrl>http://www.3rd.com</NavigateUrl>
              <
      AlternateText>3rd</AlternateText>
              <
      Impressions>10</Impressions>
              <
      Keyword></Keyword>
          </
      Ad>
      </
      Advertisements>
      In this content we assume, that 3 graphics files: 1st.jpg, 2nd.jpg, and 3rd.jpg are located in the Images subfolder.
    • Add the AdRotator control to the page. Click on it '>' small button to open the 'AdRotator Tasks' window, choose an item to create a new Data Source, choose the 'XML File' as a category and point the App_Data/Ads.xml file.

      Note, that a new component of the XmlDataSource type was created automatically.
    • Run the page, refresh it many times in a browser and note that the displayed image changes.
  5. FileUpload
    • The FileUpload control allows in a very easy way to manage a file sent by the user using standard HTML <input type="file"> mechanism.
    • Add the FileUpload control, a Button, and a Literal (the Button is needed to make send action, the Literal is used only for showing some information about the sent file):
    • The sent file must be saved manually, fortunately the FileUpload control has the SaveAs method:
      protected void Button1_Click(object sender, EventArgs e)
      {
          
      if (FileUpload1.HasFile)
          {
              
      try
              {
                  
      string destPath = Server.MapPath("~/App_Data/" + FileUpload1.FileName);
                  FileUpload1.SaveAs(destPath);

                  Literal8.Text =
      string.Format("File name: {0} <br>Size: {1} <br>Content type: {2}",
                      FileUpload1.PostedFile.FileName,
                      FileUpload1.PostedFile.ContentLength,
                      FileUpload1.PostedFile.ContentType);
              }
              
      catch (Exception ex)
              {
                  Literal8.Text =
      "ERROR: " + ex.Message.ToString();
              }
          }
          
      else
          {
              Literal8.Text =
      "No file to send.";
          }
      }
  6. Panel
    • The Panel control provides a container within the page for other controls. It allows to show and hide all contained controls, change their attributes, scroll the content, change the horizontal alignment, and set a background image. See the following example:

      protected void Button2_Click(object sender, EventArgs e)
      {
          Panel1.Visible =
      false;
      }
  7. MultiView, View
    • The MultiView and View server controls work together to enable the capability to turn on/off sections of an ASP.NET page. As an example, add the MultiView control with 3 View controls and add some controls to these Views. Add also a button which will allow to display the next view:
      <asp:MultiView ID="MultiView1" runat="server">
          <asp:View ID="View1" runat="server">
              <asp:Image ID="Image1" runat="server" ImageUrl="Images/1st.jpg" />     </asp:View>
          <asp:View ID="View2" runat="server">
              <asp:Image ID="Image2" runat="server" ImageUrl="Images/2nd.jpg" />     </asp:View>
          <asp:View ID="View3" runat="server">
              <asp:Image ID="Image3" runat="server" ImageUrl="Images/3rd.jpg" />     </asp:View>
      </
      asp:MultiView>
      <
      asp:Button ID="Button3" runat="server" Text="Next view >>"
          
      onclick="Button3_Click" />
       
      protected void Page_Load(object sender, EventArgs e)
      {
          
      if (!IsPostBack)
          {
              MultiView1.ActiveViewIndex = 0;
          }
      }
      protected void Button3_Click(object sender, EventArgs e)
      {
          
      if (MultiView1.ActiveViewIndex < MultiView1.Views.Count - 1)
          {
              MultiView1.ActiveViewIndex++;
          }
      }
  8. Wizard
    • The Wizard control can be used when there is a need for step-by-step logic. This control allows for a far greater degree of customization than does the MultiView control. As an example add the Wizard control and add some controls to its steps:
    • This control has some interesting events, e.g. FinishButtonClick:
      protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
      {
          Wizard1.Visible =
      false;
          Literal1.Visible =
      true;
      }
    • There are many formatting options available for the Wizard button. The easiest way is probably to start from the AutoFormat option:
  9. PlaceHolder
    • This control is a placeholder to interject objects dynamically into the Web page. It does not produce any visible output and is only used as a container for other controls on the Web page. Its Controls collection can be used as for any container.

      protected void Button4_Click(object sender, EventArgs e)
      {
          
      Literal literal = new Literal();
          literal.Text =
      string.Format("{0}<br>", DateTime.Now.ToString());
          PlaceHolder1.Controls.Add(literal);
      }

      Run the page. Note that after clicking the 'Add a Literal to the PlaceHolder' button, a new Literal appears in the place reserved by the PlaceHolder. Note also that after the second clicking on the button, the previously added text disappears. The reason of this behaviour is simple - each time the request is processed by the ASP.NET engine, the PlaceHolder control (as any other control) is initialized. Initialization of the PlaceHolder control used in this example does nothing - no controls are added to it. Later, after initialization and loading, the event handler adds one control, and this is the only one visible control.
  10. HiddenField
    • This control can be used to store some data at the level of a single page. For example, it can be used to solve the problem from the previous point - to allow to display all values added to the PlaceHolder control.
    • Add the HiddenField control to the page. (The place does not matter - the control is invisible.)
      <asp:HiddenField ID="HiddenField1" runat="server" />
    • Modify code in the Load event of the page and the Click event of the button:
      protected void Page_Load(object sender, EventArgs e)
      {
          
      if (!IsPostBack)
          {
              
      // previous code    }
          
      else
          {
              
      string[] texts = HiddenField1.Value.Split(';');
              
      foreach (string text in texts)
              {
                  AddToPlaceHolder(text);
              }
          }
      }
      private void AddToPlaceHolder(string text)
      {
          
      Literal literal = new Literal();
          literal.Text = text +
      "<br>";
          PlaceHolder1.Controls.Add(literal);
      }
      private void AddToHiddenField(string text)
      {
          
      if (HiddenField1.Value.Length > 0)
          {
              HiddenField1.Value +=
      ';';
          }
          HiddenField1.Value += text;
      }
      protected void Button4_Click(object sender, EventArgs e)
      {
          
      string text = DateTime.Now.ToString();
          AddToPlaceHolder(text);
          AddToHiddenField(text);
      }
      Run the page and make a few postbacks using the Button4, note that values in the PlaceHolder control are kept.
    • Very common usage of the HiddenField control is passing data from the server to the client-side code written in JavaScript and vice-versa.
[Source code]

No comments :