|
<< Click to Display Table of Contents >> Criando uma enquete mySQL com Ajax |
![]() ![]()
|
Basta criar os arquivos conforme abaixo para ter este resultado:


Banco mySQL
banco:pesquisa
CREATE TABLE `tb_filme` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`campeao` varchar(20) DEFAULT NULL,
`ip` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<connectionStrings>
<add name="conexao"
connectionString="server=localhost;User Id=root;Password=123456; Persist Security Info=True;database=pesquisa"/>
</connectionStrings>
</configuration>
Principal.aspx
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<br />
<asp:Label ID="Label1" runat="server" Text="Qual filme é melhor?"></asp:Label>
<br />
<asp:RadioButtonList ID="rblVoto" runat="server">
<asp:ListItem Value="1">Inception</asp:ListItem>
<asp:ListItem Value="2">Toy Story 3</asp:ListItem>
<asp:ListItem Value="3">Iron Man</asp:ListItem>
<asp:ListItem Value="4">Avatar</asp:ListItem>
</asp:RadioButtonList>
<br />
<asp:Label ID="lblStatus" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="btnVotar" runat="server" onclick="Votar_Click" Text="Votar" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Principal.aspx.cs
using System;
using System.Web;
namespace WebEnquete
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Votar_Click(object sender, EventArgs e)
{
string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(ip))
ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (!VerificarIP(ip))
{
Response.Redirect("Resultado.aspx?v=ok");
return;
}
if (rblVoto.SelectedItem == null)
lblStatus.Text = "Você deve selecionar uma opção!";
else
Votar(rblVoto.SelectedItem.Text, ip);
}
bool VerificarIP(string ip)
{
bool resultado;
try
{
resultado = Base.GetIPJaVotou(ip);
}
catch (Exception e)
{
lblStatus.Text = "Erro no voto (" + e.Message + ")";
resultado = false;
}
return resultado;
}
void Votar(string voto, string ip)
{
try
{
Base.GravarVoto(voto, ip);
Response.Redirect("Resultado.aspx");
}
catch (Exception e)
{
lblStatus.Text = "Erro no voto (" + e.Message + ")";
}
}
}
}
Resultados.aspx
<form id="form1" runat="server">
<div>
<asp:Label ID="lblMensagem" runat="server"></asp:Label>
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="btnExibirResultado" runat="server"
onclick="btnExibirResultado_Click" Text="Exibir resultados" />
<br />
<asp:Literal ID="litResultado" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
<a href="Principal.aspx">Principal</a></div>
</form>
Resultados.aspx.cs
using System;
using System.Drawing;
namespace WebEnquete
{
public partial class Resultado : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["v"] != null && Request.QueryString["v"].Equals("ok"))
{
lblMensagem.Text = "Você já votou!";
lblMensagem.ForeColor = Color.Red;
}
else
{
lblMensagem.Text = "Obrigado por participar";
lblMensagem.ForeColor = Color.Blue;
}
}
public void ExibirResultado()
{
litResultado.Text = Base.GetResultados();
}
protected void btnExibirResultado_Click(object sender, EventArgs e)
{
ExibirResultado();
}
}
}
Base.cs
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Data;
using System;
namespace WebEnquete
{
public static class Base
{
private static MySqlConnection conexao;
static MySqlConnection GetConnection()
{
if (conexao == null)
{
conexao = new MySqlConnection(ConfigurationManager.ConnectionStrings["Conexao"].ToString());
}
if (conexao.State != ConnectionState.Open)
conexao.Open();
return conexao;
}
public static bool GetIPJaVotou(string ip)
{
string conta;
string sql = "select count(ip) from tb_filme where ip = @ip";
using (MySqlCommand cmd = new MySqlCommand(sql, GetConnection()))
{
cmd.Parameters.AddWithValue("ip", ip);
conta = cmd.ExecuteScalar().ToString();
}
return Int32.Parse(conta) > 0;
}
public static void GravarVoto(string voto, string ip)
{
string sql = "insert into tb_filme (campeao, ip) values (@campeao, @ip)";
using (MySqlCommand command = new MySqlCommand(sql, GetConnection()))
{
command.Parameters.AddWithValue("campeao", voto);
command.Parameters.AddWithValue("ip", ip);
command.ExecuteNonQuery();
}
}
public static string GetResultados()
{
string saida = "";
string sql = "select count(ip) as qtd, " +
"(count(ip) / (select count(ip) from tb_filme)) * 100 as perc," +
"campeao from tb_filme group by campeao order by qtd desc";
using (MySqlCommand cmd = new MySqlCommand(sql, GetConnection()))
{
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
double perc = double.Parse(reader["perc"].ToString());
saida += reader["campeao"].ToString() + " - votos: " + reader["qtd"].ToString() + " - " + perc.ToString("#,##0.00") + "%" + "<br/>";
}
}
}
return saida;
}
}
}