sábado, 5 de março de 2011

MasterPage Dinâmica

Diante da dificuldade de encontrar informações de como inserir masterpage dinamicamente em uma página utilizando a função de uma classe, decidi fazer esse post.
Nesse post iremos ver como trocar a masterpage dinamicamente, a partir da opção selecionada no dropdownlist .
Crie um novo projeto e adicione duas masterpage com os seguintes nomes:  MasterBlue.master  e MasterGreen.master
No Código MasterBlue.master insira:

<%@ Master Language="VB"  Inherits="MasterBlue" CodeFile="MasterBlue.master.vb"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Master Blue</title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    Master Blue<br />
    <div style="background-color:Blue">
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>

Já na MasterGreen.master:

<%@ Master Language="VB" Inherits="MasterGreen" CodeFile="MasterGreen.master.vb"   %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">  
    <title>Master Green</title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    Master Green
    <div style="background-color:Green">
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
        </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>

Clique na solução do seu projeto e adicione uma classe com o nome TesteMaster.vb e digite o código abaixo:

Imports Microsoft.VisualBasic
Public Class TesteMaster
    Public Sub SelecionaMaster(ByRef pagina As System.Web.UI.Page, ByVal master As String)
        If master = "1" Then
            pagina.MasterPageFile = "~/MasterGreen.master"
        Else
            pagina.MasterPageFile = "~/MasterBlue.master"
        End If
    End Sub
End Class

Edite a página Default.aspx do seu projeto para que fique da seguinte forma:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="ddl_escolha" runat="server">
        <asp:ListItem Value="1">Master Green</asp:ListItem>
        <asp:ListItem Value="2">Master Blue</asp:ListItem>
    </asp:DropDownList>
    <asp:Button ID="btnOK" runat="server" Text="OK" />
    </div>
    </form>
</body>
</html>

No código Default.aspx.vb

Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub btnOK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Response.Redirect(String.Format("Default2.aspx?master={0}", Server.UrlEncode(ddl_escolha.SelectedValue)))
    End Sub
End Class

O que irá acontecer:  ao selecionar a opção do dropdownlist e clicar no botão ok, será passado o parâmetro  selecionado para classe, onde vai ser verificado qual das duas masterpage vai ser utilizada e então na página Default2.aspx ela será carregada de acordo com a opção escolhida.
Crie a página Default2.aspx e selecione uma das masterpage:

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterBlue.master" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br />
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br />
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br />
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk         MASTER PAGE DINÂMICA       kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br />
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br />
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br />
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk<br />
</asp:Content>

Note que mesmo contendo a propriedade “MasterPageFile”  no cabeçalho da página, caso a opção Master Green for escolhida no combo, será a MasterGreen.master que será carregada.
É essa propriedade é necessária na criação da pagina assim como as tags Content, onde estará o conteúdo da página.
Código Default2.aspx.vb:

Partial Class Default2
    Inherits System.Web.UI.Page
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim escolha As New TesteMaster()
        escolha.SelecionaMaster(Me, Request("master"))
    End Sub
End Class

Caso a opção Master Green seja selecionada a página Default2.aspx ficará como a imagem abaixo:

Se for a opção Master Blue ficará como a imagem abaixo:
Espero que esse post ajude muita gente.
Comentem!

sábado, 19 de fevereiro de 2011

Questionário Dinâmico em ASP.NET - Parte V

Na área do aluno temos a seguinte página aluno.aspx após o login:



<%@ Page Language="VB" AutoEventWireup="false" CodeFile="aluno.aspx.vb" Inherits="aluno" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Aluno - Home</title><style type="text/css">
    .table1
        {
            width: 680px;
            border: 1px solid #999999;
            background-color: #FFFFFF;
            font: Verdana;
            font-size: x-small;
        }
        .style2
        {
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <table align="center" class="table1" style="font-family: Verdana; font-size: x-small;">
        <tr>
            <td style="text-align: left">&nbsp;</td>
        </tr>
        <tr>
            <td class="style2">
                <asp:Button ID="Button2" runat="server" Text="Questionário" PostBackUrl="~/questionario_teste.aspx" />
            </td>
        </tr>
        <tr>
            <td style="text-align: center">&nbsp;</td>
        </tr>
        <tr>
            <td style="text-align: center">
                  <asp:Button ID="Button5" runat="server" Text="Home" />
                  &nbsp;
<asp:Button ID="Button6" runat="server" Text="Sair" PostBackUrl="Default.aspx" />
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>


Ao clicar em questionário e selecionar o tema, as questões serão exibidas, basta selecionar a alternativa correta para cada questão e clicar no botão responder.



Será exibida a mensagem “Questionário respondido com sucesso” conforme a imagem abaixo:



Segue o código da página questionario.aspx:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="questionario.aspx.vb" Inherits="questionario" %>

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

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Aluno - Questionário</title>
<style type="text/css">
.table1
        {
            width: 680px;
            border: 1px solid #999999;
            background-color: #FFFFFF;
            font: Verdana;
            font-size: x-small;
        }
        .style3
        {
            text-align: left;
        }
        </style>
</head>
<body style="text-align: center">
    <form id="form1" runat="server">
    <div>
   
    <table align="center" class="table1" style="font-family: Verdana; font-size: x-small;">
        <tr>
            <td style="text-align: left">&nbsp;</td>
        </tr>
        <tr>
            <td style="text-align: center">
                <asp:Button ID="Button5" runat="server" PostBackUrl="~/aluno.aspx"
                    Text="Home" />
            </td>
        </tr>
        <tr>
            <td style="text-align: center">&nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                Selecione o tema:                
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="AccessDataSource1" DataTextField="tema" DataValueField="id" AutoPostBack="True">
                </asp:DropDownList>
                <asp:AccessDataSource ID="AccessDataSource1" runat="server"
                    DataFile="~/projeto.mdb" SelectCommand="SELECT * FROM [tema_questao]">
                </asp:AccessDataSource>
            </td>
        </tr>
        <tr>
            <td class="style3">&nbsp;</td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Repeater ID="Repeater1" runat="server" DataSourceID="AccessDataSource2">
                    <ItemTemplate>
                    <table>
                    <tr>
            <td class="style3" colspan="2"></td>
        </tr>
        <tr>
            <td colspan="2"></td>
        </tr>
  <tr>
            <td colspan="2">
                <asp:Label ID="lbl_numquestao" runat="server" Text='<%#Eval("num_questao")%>'>
                </asp:Label> -
                <asp:Label ID="lbl_questao" runat="server" Text='<%#Eval("questao")%>'></asp:Label>
                </td>
        </tr>
        <tr>
            <td rowspan="4">
                <asp:RadioButtonList ID="rbl_resposta" runat="server" TextAlign="Left" Height="100%">
                    <asp:ListItem>A</asp:ListItem>
                    <asp:ListItem>B</asp:ListItem>
                    <asp:ListItem>C</asp:ListItem>
                    <asp:ListItem>D</asp:ListItem>
                </asp:RadioButtonList>
            </td>
            <td>
                <asp:Label ID="Label4" runat="server" Text='<%#Eval("alternativa1")%>'></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Label5" runat="server" Text='<%#Eval("alternativa2")%>'></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Label6" runat="server" Text='<%#Eval("alternativa3")%>'></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="Label7" runat="server" Text='<%#Eval("alternativa4")%>'></asp:Label>
            </td>
        </tr>
                    </table>
                </ItemTemplate>
                </asp:Repeater>
                <asp:AccessDataSource ID="AccessDataSource2" runat="server"
                    DataFile="~/projeto.mdb"
                    SelectCommand="SELECT [id_tema], [num_questao], [questao], [alternativa1], [alternativa2], [alternativa3], [alternativa4] FROM [questoes] WHERE ([id_tema] = ?) order by num_questao">
                    <SelectParameters>
                        <asp:ControlParameter ControlID="DropDownList1" Name="id_tema"
                            PropertyName="SelectedValue" Type="String" />
                    </SelectParameters>
                </asp:AccessDataSource>
            </td>
        </tr>
        <tr>
            <td class="style3">
                <asp:Button ID="Button6" runat="server" Text="Responder" />
            </td>
        </tr>
        <tr>
            <td class="style3">&nbsp;</td>
        </tr>
       
    </table>
</div>
    </form>
</body>
</html>

Na página questionario.aspx.vb inserir:

Imports System.Data.OleDb
Imports System.Data

Partial Class questionario
    Inherits System.Web.UI.Page

    Protected Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button6.Click

        Dim conexao As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("projeto.mdb"))
        Dim cmd As New OleDbCommand

        Session("tema") = DropDownList1.SelectedValue

        conexao.Open()
        cmd.Connection = conexao

        Dim item As RepeaterItem
        For Each item In Repeater1.Items
            Dim nquest As String = CType(item.FindControl("lbl_numquestao"), Label).Text
            Dim resp As String = CType(item.FindControl("rbl_resposta"), RadioButtonList).SelectedValue
            cmd.CommandText = "Insert into questionario_respondido(login,id_tema,questao,resposta)values('" & Session("login") & "', '" & Session("tema") & "', '" & nquest & "', '" & resp & "')"

            cmd.ExecuteNonQuery()
        Next item

        Dim texto As String
        texto = "Questionário respondido com sucesso!"
        ScriptManager.RegisterClientScriptBlock(Me, Me.GetType, "Error", "alert('" & texto & "'); window.location.href = 'aluno.aspx';", True)

    End Sub
End Class

Espero que tenham gostado e comentem!
Finalmente a última parte deste post, obrigada a todos que acompanharam pacientemente!