Os elementos de controles web em ASP.NET são denominados ASP.NET Web server controls, são executados quando a página é requisitada e que processa a marcação para um navegador. Muitos controles se assemelham à elementos HTML, como botões e caixas de texto . Outros controles possuem comportamento complexo, como os controles de calendário, e os controles que gerenciam conexões de dados. Você pode criar uma paginas web facilmente com os controles ASP.NET, você pode ainda mixar os controles ASP.NET com elementos HTML ou de outros Frameworks, pois além dos elementos serem intuitivos ainda contam com uma ótima interface visual RAD proporcionada pelo Visual Studio que poupará tempo significativo no desenvolvimento de suas aplicações.
Usando Elementos e Controles
1 – Crie uma aplicação ASP.NET do tipo C# Empty e crie duas paginas ASPX, uma chamada default.aspx e a outra resultado.aspx. Crie também uma classe C# para o objeto chamado Participante que será responsável pelos dados do cadastro. Utilize o código abaixo para cada respectivo arquivo e rode sua aplicação:
2 – Assim que o usuário preencher os dados corretamente será redirecionado para a pagina de resultado que mostrará o conteúdo do objeto na sessão do navegador web.
Exemplo:
Neste exemplo criamos um formulário utilizando os elementos HTML e controles ASP.NET para criar um cadastro que valida os tipos de entrada do usuário, através dos elementos criados pelos controles ASP.NET.
Objeto – Participante
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DAWebApp001 { public class Participante { // Declara atributos publicos private long id; private string nome; private string sobrenome; private string cargo; private DateTime data; private double salario; private string genero; private Boolean ativo; private string observacao; // Declara propriedades public long Id { get { return id; } set { id = value; } } public string Nome { get { return nome; } set { nome = value; } } public string Sobrenome { get { return sobrenome; } set { sobrenome = value; } } public string Cargo { get { return cargo; } set { cargo = value; } } public DateTime Data { get { return data; } set { data = value; } } public double Salario { get { return salario; } set { salario = value; } } public string Genero { get { return genero; } set { genero = value; } } public Boolean Ativo { get { return ativo; } set { ativo = value; } } public string Observacao { get { return observacao; } set { observacao = value; } } } }
Página – default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="DAWebApp001._default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .auto-style2 { width: 14%; } .auto-style3 { height: 23px; } .auto-style5 { width: 248px; } .auto-style6 { width: 54%; } .auto-style8 { height: 23px; width: 54%; } .auto-style9 { height: 23px; width: 248px; } </style> </head> <body> <h1>Desenvolvimento Aberto - ASP.NET</h1> <h2>Cadastro - Controles - ASP.NET</h2> <form id="form1" runat="server"> <div> <fieldset style="padding: 20px"> <legend style="padding: 5px">Cadastro</legend> <table style="width: 100%;"> <tr> <td class="auto-style3" colspan="2"> <asp:Label ID="LabelMenssagem" runat="server" Text="Entre com os dados abaixo:"></asp:Label> </td> <td class="auto-style8"></td> </tr> <tr> <td class="auto-style2"> <asp:Label ID="Label2" runat="server" Text="Nome:"></asp:Label> </td> <td class="auto-style5"> <asp:TextBox ID="TextBox1nome" runat="server" Width="142px"></asp:TextBox> </td> <td class="auto-style6"> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1nome" ErrorMessage="Nome é obrigatório." ForeColor="Red" ValidationGroup="AllValidator"></asp:RequiredFieldValidator> <br /> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1nome" ErrorMessage="Permitido somente caractere alphanumericos" ForeColor="Red" ValidationExpression="[a-zA-Z]+" ValidationGroup="AllValidator"></asp:RegularExpressionValidator> </td> </tr> <tr> <td class="auto-style3"> <asp:Label ID="Label3" runat="server" Text="Sobrenome:"></asp:Label> </td> <td class="auto-style9"> <asp:TextBox ID="TextBox2sobrenome" runat="server" Width="240px"></asp:TextBox> </td> <td class="auto-style8"> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2sobrenome" ErrorMessage="Sobrenome é obrigatório." ForeColor="Red" ValidationGroup="AllValidator"></asp:RequiredFieldValidator> <br /> <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="TextBox2sobrenome" ErrorMessage="Permitido somente caractere alphanumericos" ForeColor="Red" ValidationExpression="[a-zA-Z]+" ValidationGroup="AllValidator"></asp:RegularExpressionValidator> </td> </tr> <tr> <td class="auto-style3"> <asp:Label ID="Label4" runat="server" Text="Cargo:"></asp:Label> </td> <td class="auto-style9"> <asp:DropDownList ID="DropDownList1" runat="server" Height="16px" Width="211px"> <asp:ListItem></asp:ListItem> <asp:ListItem>Vocalista</asp:ListItem> <asp:ListItem>Guitarrista</asp:ListItem> <asp:ListItem>Baixista</asp:ListItem> <asp:ListItem>Baterista</asp:ListItem> </asp:DropDownList> </td> <td class="auto-style8"> <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Cargo é obrigatório." ForeColor="Red" ValidationGroup="AllValidator"></asp:RequiredFieldValidator> <br /> <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ControlToValidate="DropDownList1" ErrorMessage="Permitido somente caractere alphanumericos" ForeColor="Red" ValidationExpression="[a-zA-Z]+" ValidationGroup="AllValidator"></asp:RegularExpressionValidator> </td> </tr> <tr> <td class="auto-style3"> <asp:Label ID="Label6" runat="server" Text="Data de Admissão:"></asp:Label> </td> <td class="auto-style9"> <asp:TextBox ID="TextBox1Data" runat="server" Width="177px"></asp:TextBox> </td> <td class="auto-style8"> <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="TextBox1Data" ErrorMessage="Data de admissão é obrigatória." ForeColor="Red" ValidationGroup="AllValidator"></asp:RequiredFieldValidator> <br /> <asp:RegularExpressionValidator ID="RegularExpressionValidator5" runat="server" ControlToValidate="TextBox1Data" ErrorMessage="Formato de data invalido, use (dd/mm/yyyy)." ForeColor="Red" ValidationExpression="^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$" ValidationGroup="AllValidator"></asp:RegularExpressionValidator> </td> </tr> <tr> <td class="auto-style3"> <asp:Label ID="Label5" runat="server" Text="Salário:"></asp:Label> </td> <td class="auto-style9"> <asp:TextBox ID="TextBox4salario" runat="server"></asp:TextBox> </td> <td class="auto-style8"> <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox4salario" ErrorMessage="Salário é obrigatório. " ForeColor="Red" ValidationGroup="AllValidator"></asp:RequiredFieldValidator> <br /> <asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ControlToValidate="TextBox4salario" ErrorMessage="Permitido somente caractere numericos e decimais." ForeColor="Red" ValidationExpression="(?:\d*\.)?\d+" ValidationGroup="AllValidator"></asp:RegularExpressionValidator> </td> </tr> <tr> <td class="auto-style3"> <asp:Label ID="Label7" runat="server" Text="Sexo:"></asp:Label> </td> <td class="auto-style9"> <asp:RadioButton ID="RadioButton1" runat="server" GroupName="Grupo1" Text="Masculino" /> <asp:RadioButton ID="RadioButton2" runat="server" GroupName="Grupo1" Text="Feminino" /> </td> <td class="auto-style8"> <br /> </td> </tr> <tr> <td class="auto-style3"> <asp:Label ID="Label8" runat="server" Text="Ativo:"></asp:Label> </td> <td class="auto-style9"> <asp:CheckBox ID="CheckBox1" runat="server" Text="Cadastro Valido" /> </td> <td class="auto-style8"> <br /> </td> </tr> <tr> <td class="auto-style3"> <asp:Label ID="Label9" runat="server" Text="Observação:"></asp:Label> </td> <td class="auto-style9"> <asp:TextBox ID="TextBox1Observacao" runat="server" Columns="40" Rows="5" TextMode="MultiLine"></asp:TextBox> </td> <td class="auto-style8"> </td> </tr> <tr> <td class="auto-style3" colspan="3"> <hr /> </td> </tr> <tr> <td class="auto-style3"> <asp:Button ID="Button1enviardados" runat="server" Text="Enviar Dados" OnClick="Button1enviardados_Click" ValidationGroup="AllValidator" /> </td> <td class="auto-style9"> </td> <td class="auto-style8"> </td> </tr> </table> </fieldset> </div> </form> </body> </html>
Página – default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DAWebApp001 { public partial class _default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Participante participante = new Participante(); Session["Cadastro"] = participante; } protected void Button1enviardados_Click(object sender, EventArgs e) { if (Page.IsValid) { // Recupera objeto da Session Participante cad = (Participante)Session["Cadastro"]; // Valor normalmente é um autoincremento // Ou pelo banco Identity (MSSQL) Sequence (Oracle, DB2, etc) // Ou algum framework ORM - NUNCA faça um autoincremento manualmente na aplicação cad.Id = 1; // Alimenta Objeto cad.Nome = TextBox1nome.Text; cad.Sobrenome = TextBox2sobrenome.Text; cad.Cargo = DropDownList1.Text; cad.Data = DateTime.Parse(TextBox1Data.Text); cad.Salario = Double.Parse(TextBox4salario.Text); // Verifica valores boleanos if (RadioButton1.Checked) { cad.Genero = RadioButton1.Text; } if (RadioButton2.Checked) { cad.Genero = RadioButton2.Text; } cad.Ativo = CheckBox1.Checked; cad.Observacao = TextBox1Observacao.Text; // Redireciona pagina Response.Redirect("resultado.aspx"); } } } }
Página – resultado.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="resultado.aspx.cs" Inherits="DAWebApp001.resultado" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <style type="text/css"> .auto-style1 { width: 143px; } .auto-style2 { width: 143px; height: 23px; } .auto-style3 { height: 23px; } </style> </head> <body> <form id="form1" runat="server"> <div> <h1>Desenvolvimento Aberto - ASP.NET</h1> <h2>Cadastro - Controles - ASP.NET - Resultado</h2> <table style="width: 100%;"> <tr> <td class="auto-style1"> <asp:Label ID="Label1" runat="server" Text="Nome:"></asp:Label> </td> <td> <asp:Label ID="lnome" runat="server" Text="Label"></asp:Label> </td> <td> </td> </tr> <tr> <td class="auto-style1"> <asp:Label ID="Label2" runat="server" Text="Sobrenome:"></asp:Label> </td> <td> <asp:Label ID="lsobrenome" runat="server" Text="Label"></asp:Label> </td> <td> </td> </tr> <tr> <td class="auto-style2"> <asp:Label ID="Label3" runat="server" Text="Cargo:"></asp:Label> </td> <td class="auto-style3"> <asp:Label ID="Lcargo" runat="server" Text="Label"></asp:Label> </td> <td class="auto-style3"></td> </tr> <tr> <td class="auto-style1"> <asp:Label ID="Label4" runat="server" Text="Data de Admissão:"></asp:Label> </td> <td> <asp:Label ID="ldata" runat="server" Text="Label"></asp:Label> </td> <td> </td> </tr> <tr> <td class="auto-style1"> <asp:Label ID="Label5" runat="server" Text="Salário:"></asp:Label> </td> <td> <asp:Label ID="lsalario" runat="server" Text="Label"></asp:Label> </td> <td> </td> </tr> <tr> <td class="auto-style1"> <asp:Label ID="Label6" runat="server" Text="Sexo:"></asp:Label> </td> <td> <asp:Label ID="lgenero" runat="server" Text="Label"></asp:Label> </td> <td> </td> </tr> <tr> <td class="auto-style2"> <asp:Label ID="Label7" runat="server" Text="Ativo:"></asp:Label> </td> <td class="auto-style3"> <asp:Label ID="lativo" runat="server" Text="Label"></asp:Label> </td> <td class="auto-style3"></td> </tr> <tr> <td class="auto-style1"> <asp:Label ID="Label8" runat="server" Text="Observação:"></asp:Label> </td> <td> <asp:Label ID="lobservacao" runat="server" Text="Label"></asp:Label> </td> <td> </td> </tr> <tr> <td class="auto-style1"> </td> <td> </td> <td> </td> </tr> </table> <br /> </div> </form> </body> </html>
Página – resultado.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace DAWebApp001 { public partial class resultado : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Recupera objeto Participante cad = (Participante)Session["Cadastro"]; if (Session["Cadastro"] != null) { // Alimemta valores lnome.Text = cad.Nome; lsobrenome.Text = cad.Sobrenome; Lcargo.Text = cad.Cargo; ldata.Text = cad.Data.ToString(); lsalario.Text = cad.Salario.ToString(); lgenero.Text = cad.Genero; lativo.Text = cad.Ativo.ToString(); lobservacao.Text = cad.Observacao; } } } }
Web.config
<?xml version="1.0" encoding="utf-8"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> </system.web> <appSettings> <add key="ValidationSettings:UnobtrusiveValidationMode" value="None"/> </appSettings> </configuration>