본문 바로가기

   
Programming/ASP.NET(4.0)

ASP.NET Cookie, ViewState 사용예제

반응형

ASP.NET Cookie, ViewState 사용예제

로그인상태유지도 쿠키로 처리한다 


아이디기억 전제조건 로그인성공시에 


누군가 접속을 하게 되면 세션객체가 각각 생성됨(연결은 되어있지 않는 상태) 20분동안

재접속

세션아이디를 쿠키로 돌려준다 그래서 연결이 끊겼다 재요청이 됐을때 이전에 방문자라고 기억하는 이유는 쿠키값 때문이다.


ViewState는 자기페이만의 것이다. 지역변수 개념 페이지안에서밖에 상태유지가 안된다. 2단계 viewState 복구단계에서 없어진 갑이 복구된다.


비교


Application 전역변수 공용변수 Object 서버

Session 전역변수 개인변수 Object 서버

Cookie 전역변수 개인변수 String 클라이언트

ViewState 지역변수 개인변수 Object 클라이언트





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex50_Cookie.aspx.cs" Inherits="Ex50_Cookie" %>

 

<!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>

   

       <h2>

                    Ex50_Cookie.aspx</h2>

             <br />

             <br />

             Cookie = Session 유사<br />

             <br />

             <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class Ex50_Cookie : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             // 쿠키 - txt파일

             // : 텍스트를 저장 가능한 공간

             // : , 클라이언트측에 저장되는 공간

             // 1. 메모리 쿠키 : 기본(브라우저 프로세스안에 저장, 메모리)

             // 브라우저가 살아있을 동안만 유지됨

 

             // 2. 하드 쿠키 : 지정(유효기간)

 

             //세션 - 서버메모리

             // : Object를 저장 가능한 공간

             // : , 서버측에 저장되는 공간

 

             //쿠키 저장(string)

             Response.Cookies["name"].Value = "zzarungna";

 

             //유효기간 설정

             //요효기간이 오버되면 자동 삭제된다.

             //Response.Cookies["name"].Expires = new DateTime(2012, 12, 31);

             Response.Cookies["name"].Expires = DateTime.Now.AddYears(1);//현재로부터 1년간 보존

 

             //쿠키읽기

             Label1.Text = Request.Cookies["name"].Value;

    }

}

 





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex50_Cookie.aspx.cs" Inherits="Ex50_Cookie" %>

 

<!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>

   

       <h2>

                    Ex50_Cookie.aspx</h2>

             <h2>

                    <br />

                    Cookie = Session 유사<br />

                    페이지가 실행되는 순간 txt 파일생성 되면서 정보도 같이 생성<br />

                    <br />

                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

             </h2>

             <br />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class Ex50_Cookie : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             //쿠키 - txt파일

             // : 텍스트를 저장 가능한 공간

             // : , 클라이언트측에 저장되는 공간

             // 1. 메모리 쿠키 : 기본(브라우저 프로세스안에 저장, 메모리)

             // 2. 하드 쿠키 : 지정(유효기간) -> 메모리 쿠키

 

             //세션 - 서버메모리

             // : Object를 저장 가능한 공간

             // : , 서버측에 저장된는 공간

 

             //쿠키 저장(string)

             Response.Cookies["name"].Value = "hong";

 

             //유효기간 설정

             //Response.Cookies["name"].Expires = new DateTime(2012, 12, 31);

             Response.Cookies["name"].Expires = DateTime.Now.AddYears(1);//현재로부터 1년간 보존

 

             //쿠키 읽기 - 한글 인코딩

             Label1.Text = Request.Cookies["name"].Value;

    }

}

 




check

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex50_Check.aspx.cs" Inherits="Ex50_Check" %>

 

<!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 id="body" runat="server">

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

    <div>

   

       <h2>

                    Ex50_Check.aspx</h2>

             <br />

             <h2>

                    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

             </h2>

             <br />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class Ex50_Check : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (Request.Cookies["name"] != null)

                    Label1.Text = Request.Cookies["name"].Value;

 

 

             //Ex51에서 저장한 쿠키를 읽어서 현재 페이지의 배경으로 세팅

             if (Request.Cookies["back"] != null)

                   body.Attributes["background"] = "images/" + Request.Cookies["back"].Value;

    }

}

 




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex51_Cookie.aspx.cs" Inherits="Ex51_Cookie" %>

 

<!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>

       <style type="text/css">

            

            

             table

             {

                    background-color:White;

             }

            

             .style1

             {

                    width: 500px;

                    border-collapse: collapse;

                    border: 1px solid #000000;

             }

             .style2

             {

                    width: 128px;

                    height: 128px;

             }

       </style>

</head>

<body id="body" runat="server">

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

    <div>

   

       <h2>

                    Ex51_Cookie.aspx</h2>

             <br />

             <h2>

                    우리 사이트의 배경이미지 선택</h2>

             <table class="style1">

                    <tr>

                           <td>

                                 <img alt="" class="style2" src="images/adore.png" /></td>

                           <td>

                                 <img alt="" class="style2" src="images/angry.png" /></td>

                           <td>

                                 <img alt="" class="style2" src="images/cool.png" /></td>

                    </tr>

                    <tr>

                           <td>

                                 <asp:RadioButton ID="RadioButton1" runat="server" Checked="True"

                                        GroupName="back" AutoPostBack="True" oncheckedchanged="RadioButton1_CheckedChanged" />

                           </td>

                           <td>

                                 <asp:RadioButton ID="RadioButton2" runat="server" GroupName="back"

                                        AutoPostBack="True" oncheckedchanged="RadioButton2_CheckedChanged" />

                           </td>

                           <td>

                                 <asp:RadioButton ID="RadioButton3" runat="server" GroupName="back"

                                        AutoPostBack="True" oncheckedchanged="RadioButton3_CheckedChanged" />

                           </td>

                    </tr>

             </table>

             <br />

             <br />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class Ex51_Cookie : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             if (!IsPostBack)

             {

                    if (Request.Cookies["back"] != null)

                    {

                           body.Attributes["background"] = "images/" + Request.Cookies["back"].Value;

 

                           //라디오버튼 초기화

                           if (Request.Cookies["back"].Value == "adore.png")

                                 RadioButton1.Checked = true;

                           else if (Request.Cookies["back"].Value == "angry.png")

                                 RadioButton2.Checked = true;

                           else if (Request.Cookies["back"].Value == "cool.png")

                                 RadioButton3.Checked = true;

                    }

                    else

                           body.Attributes["background"] = "images/adore.png";

             }

    }

       protected void RadioButton2_CheckedChanged(object sender, EventArgs e)

       {

             //체크O, 체크X 발생

             if (RadioButton2.Checked)

             {

                    //배경 이미지 바꾸기(태그 속성 or CSS)

                    body.Attributes["background"] = "images/angry.png";

                    //body.Style["background-image"] = "url(images/angry.png)";

 

                    Response.Cookies["back"].Value = "angry.png";

                    Response.Cookies["back"].Expires = DateTime.Now.AddMonths(1);//한달동안..

             }

       }

       protected void RadioButton1_CheckedChanged(object sender, EventArgs e)

       {

             if (RadioButton1.Checked)

             {

                    body.Attributes["background"] = "images/adore.png";

                    //배경이미지 기억 -> 쿠키저장

                    Response.Cookies["back"].Value = "adore.png";

                    Response.Cookies["back"].Expires = DateTime.Now.AddMonths(1);//한달동안..

             }

       }

       protected void RadioButton3_CheckedChanged(object sender, EventArgs e)

       {

             if (RadioButton3.Checked)

             {

                    body.Attributes["background"] = "images/cool.png";

                    Response.Cookies["back"].Value = "cool.png";

                    Response.Cookies["back"].Expires = DateTime.Now.AddMonths(1);//한달동안..

             }

       }

}

 











<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex52_Cookie.aspx.cs" Inherits="Ex52_Cookie" %>

 

<!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>

   

       <br />

             아이디 :

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

             <br />

             <br />

             암호&nbsp;&nbsp; :

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

             <br />

             <br />

             <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="로그인" />

             <br />

             <br />

             <asp:CheckBox ID="CheckBox1" runat="server" Text="아이디 기억하기" />

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class Ex52_Cookie : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

             //첫요청일 경우 쿠키 있는지? -> 있으면 아이디를 초기값 세팅, 없으면..

             if (!IsPostBack)

             {

                    if (Request.Cookies["id"] != null)

                    {

                           TextBox1.Text = Request.Cookies["id"].Value;

                           CheckBox1.Checked = true;

                    }

                   

             }

    }

       protected void Button1_Click(object sender, EventArgs e)

       {

             //로그인

             if (TextBox1.Text == "test" && TextBox2.Text == "1111")

             {

                    //로그인 성공

 

                    //아이디 기억하기?

                    if (CheckBox1.Checked == true)

                    {

                           //기억 -> 쿠키 저장

                           Response.Cookies["id"].Value = TextBox1.Text;

                           Response.Cookies["id"].Expires = DateTime.Now.AddMonths(1);

                    }

                    else

                    {

                           //기억안함, 쿠키삭제 -> 불가능(삭제명령이 없다.)

                           // : 유효기간이 만료되어야만 삭제

                           //MinValue = 서기11개월 1

                           //Response.Cookies["id"].Expires = DateTime.MinValue;

                           Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1);

 

                    }

             }

       }

}

 









<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ex53_ViewState.aspx.cs" Inherits="Ex53_ViewState" %>

 

<!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>

   

       <h2>

                    Ex53_ViewState.aspx</h2>

             ViewState<br />

             1. 컨트롤의 상태 유지를 가능하게 한다.<br />

             2. ViewState의 일부를 우리가 사용 가능하다.<br />

             <br />

             <br />

             <br />

             <br />

             <br />

             <br />

             <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

             <br />

             <br />

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

             <br />

             <br />

   

    </div>

    </form>

</body>

</html>

 

 



using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public partial class Ex53_ViewState : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

             List<string> List = null;

 

             if (!IsPostBack)

              {

                    //ViewState 저장

                    ViewState["num"] = 100;

 

                    List = new List<string>();

                    List.Add("아무게");

                    List.Add("홍길동");

 

                    ViewState["list"] = List;//객체저장

                   

             }

 

             else

             {

                    Label1.Text = ViewState["num"].ToString();

 

                    List = (List<string>)ViewState["list"];

                   

                    Label1.Text = List[0];    

 

                   

             }

    }

       protected void Button1_Click(object sender, EventArgs e)

       {

 

       }

}

 



반응형