[C#/ASP.NET] “…bin/roslyn/csc.exe” 경로의 일부를 찾을 수 없습니다
■ "…bin/roslyn/csc.exe" 경로의 일부를 찾을 수 없습니다. [조치 사항] 1. 비주얼 스튜디오에서 [도구/NuGet 패키지 관리/패키지 관리자 콘솔] 메뉴를 클릭한다. 2. 아래 명령을
■ "…bin/roslyn/csc.exe" 경로의 일부를 찾을 수 없습니다. [조치 사항] 1. 비주얼 스튜디오에서 [도구/NuGet 패키지 관리/패키지 관리자 콘솔] 메뉴를 클릭한다. 2. 아래 명령을
■ WebClient 클래스의 UploadValues 메소드를 사용해 폼 데이터를 전송하는 방법을 보여준다. [TestServer 프로젝트] ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestServer.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>HttpRequest 클래스 : Form 속성을 사용해 전송 데이터 구하기</title> </head> <body> <form id="form" runat="server"> <div> 사용자 ID : <asp:TextBox ID="userIDTextBox" runat="server" /> <br /> 패스워드 : <asp:TextBox ID="passwordTextBox" runat="server" /> <br /> 이름 : <asp:TextBox ID="nameTextBox" runat="server" /> <br /> 나이 : <asp:TextBox ID="ageTextBox" runat="server" /> <br /> <br /> <asp:Button ID="submitButton" runat="server" Text="제출" OnClick="submitButton_Click" /> </div> </form> </body> </html> |
▶ MainPage.axpx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
using System; using System.Web.UI; namespace TestServer { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(Request.Form != null && Request.Form.Count > 0) { string userID = Request.Form["userIDTextBox" ]; string password = Request.Form["passwordTextBox"]; string name = Request.Form["nameTextBox" ]; string age = Request.Form["ageTextBox" ]; string message = string.Format ( "사용자 ID : {0}<br />패스워드 : {1}<br />이름 : {2}<br />나이 : {3}<br /><br />", userID, password, name, age ); Response.Write(message); } } #endregion #region 제출 버튼 클릭시 처리하기 - submitButton_Click(object sender, EventArgs e) /// <summary> /// 제출 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void submitButton_Click(object sender, EventArgs e) { } #endregion } } |
[TestClient 프로젝트] ▶
■ SignalR 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ ASP.NET 게시판을 사용하는 방법을 보여준다. ▶ TestDB.sql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
CREATE TABLE dbo.Notice ( ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY -- ID ,[Name] NVARCHAR(25) NOT NULL -- 작성자명 ,MailAddress NVARCHAR(100) NULL -- 메일 주소 ,Title NVARCHAR(150) NOT NULL -- 제목 ,WriteDate DATETIME DEFAULT GETDATE() NOT NULL -- 작성일 ,WriteIP NVARCHAR(15) NULL -- 작성 IP ,Content NTEXT NOT NULL -- 내용 ,[Password] NVARCHAR(20) NULL -- 패스워드 ,ReadCount INT DEFAULT 0 -- 조회 수 ,[Encoding] NVARCHAR(10) NOT NULL -- 인코딩(HTML/TEXT) ,Homepage NVARCHAR(100) NULL -- 홈페이지 ,UpdateDate DATETIME NULL -- 수정일 ,UpdateIP NVARCHAR(15) NULL -- 수정 IP ,[FileName] NVARCHAR(255) NULL -- 파일명 ,FileSize INT DEFAULT 0 -- 파일 크기 ,DownloadCount INT DEFAULT 0 -- 다운로드 수 ,ReferenceID INT NOT NULL -- 참조 ID ,ReplyLevel INT DEFAULT 0 -- 답변 레벨 ,ReplyOrder INT DEFAULT 0 -- 답변 순서 ,ReplyCount INT DEFAULT 0 -- 답변 수 ,ParentID INT DEFAULT 0 -- 부모 ID ,CommentCount INT DEFAULT 0 -- 댓글 수 ) GO CREATE TABLE dbo.NoticeComment ( ID INT IDENTITY(1, 1) NOT NULL PRIMARY KEY -- ID ,NoticeID INT NOT NULL -- 게시판 ID ,[Name] NVARCHAR(25) NOT NULL -- 작성자명 ,Comment NVARCHAR(4000) NOT NULL -- 내용 ,WriteDate SMALLDATETIME DEFAULT(GETDATE()) -- 작성일 ,[Password] NVARCHAR(20) NOT NULL -- 패스워드 ) GO CREATE PROCEDURE dbo.WriteNotice @Name NVARCHAR(25) ,@MailAddress NVARCHAR(100) ,@Title NVARCHAR(150) ,@WriteIP NVARCHAR(15) ,@Content NTEXT ,@Password NVARCHAR(20) ,@Encoding NVARCHAR(10) ,@Homepage NVARCHAR(100) ,@FileName NVARCHAR(255) ,@FileSize INT AS DECLARE @MaximumReferenceID INT; SELECT @MaximumReferenceID = MAX(ReferenceID) FROM dbo.Notice; IF @MaximumReferenceID IS NULL BEGIN SET @MaximumReferenceID = 1; END ELSE BEGIN SET @MaximumReferenceID = @MaximumReferenceID + 1; END INSERT INTO dbo.Notice ( [Name] ,MailAddress ,Title ,WriteIP ,Content ,[Password] ,[Encoding] ,Homepage ,[ReferenceID] ,[FileName] ,[FileSize] ) Values ( @Name ,@MailAddress ,@Title ,@WriteIP ,@Content ,@Password ,@Encoding ,@Homepage ,@MaximumReferenceID ,@FileName ,@FileSize ); GO CREATE PROCEDURE dbo.ListNotice @Page INT AS WITH OrderedNoticeBoard AS ( SELECT ID ,[Name] ,MailAddress ,Title ,WriteDate ,ReadCount ,ReferenceID ,ReplyLevel ,ReplyOrder ,ReplyCount ,ParentID ,CommentCount ,[FileName] ,FileSize ,DownloadCount ,ROW_NUMBER() OVER (ORDER BY ReferenceID DESC, ReplyOrder ASC) AS 'RowNumber' FROM dbo.Notice ) SELECT * FROM OrderedNoticeBoard WHERE RowNumber BETWEEN @Page * 10 + 1 AND (@Page + 1) * 10; GO CREATE PROCEDURE dbo.ViewNotice @ID Int As UPDATE dbo.Notice SET ReadCount = ReadCount + 1 WHERE ID = @ID; SELECT * FROM dbo.Notice WHERE ID = @ID; GO CREATE PROCEDURE dbo.ReplyNotice @Name NVARCHAR(25) ,@MailAddress NVARCHAR(100) ,@Title NVARCHAR(150) ,@WriteIP NVARCHAR(15) ,@Content NTEXT ,@Password NVARCHAR(20) ,@Encoding NVARCHAR(10) ,@Homepage NVARCHAR(100) ,@ParentID INT ,@FileName NVARCHAR(255) ,@FileSize INT AS DECLARE @MaximumReplyOrder INT; DECLARE @MaximumReplyCount INT; DECLARE @ParentReferenceID INT; DECLARE @ParentReplyLevel INT; DECLARE @ParentReplyOrder INT; UPDATE dbo.Notice Set ReplyCount = ReplyCount + 1 WHERE ID = @ParentID; SELECT @MaximumReplyOrder = ReplyOrder ,@MaximumReplyCount = ReplyCount FROM dbo.Notice WHERE ParentID = @ParentID AND ReplyOrder = (SELECT MAX(ReplyOrder) FROM dbo.Notice WHERE ParentID = @ParentID); IF @MaximumReplyOrder IS NULL BEGIN SELECT @MaximumReplyOrder = ReplyOrder FROM dbo.Notice WHERE ID = @ParentID; SET @MaximumReplyCount = 0; END SELECT @ParentReferenceID = ReferenceID ,@ParentReplyLevel = ReplyLevel FROM dbo.Notice WHERE ID = @ParentID; UPDATE dbo.Notice SET ReplyOrder = ReplyOrder + 1 WHERE ReferenceID = @ParentReferenceID And ReplyOrder > (@MaximumReplyOrder + @MaximumReplyCount); INSERT INTO dbo.Notice ( [Name] ,MailAddress ,Title ,WriteIP ,Content ,[Password] ,[Encoding] ,Homepage ,ReferenceID ,ReplyLevel ,ReplyOrder ,ParentID ,[FileName] ,FileSize ) VALUES ( @Name ,@MailAddress ,@Title ,@WriteIP ,@Content ,@Password ,@Encoding ,@Homepage ,@ParentReferenceID ,@ParentReplyLevel + 1 ,@MaximumReplyOrder + @MaximumReplyCount + 1 ,@ParentID ,@FileName ,@FileSize ); GO CREATE PROCEDURE dbo.GetNoticeCount As Select Count(*) From dbo.Notice; GO CREATE PROCEDURE dbo.SearchNoticeCount @SearchField NVARCHAR(25) ,@SearchQuery NVARCHAR(25) AS SET @SearchQuery = '%' + @SearchQuery + '%'; SELECT COUNT(*) FROM dbo.Notice WHERE ( CASE @SearchField WHEN 'Name' THEN [Name] WHEN 'Title' THEN Title WHEN 'Content' THEN Content ELSE @SearchQuery END ) LIKE @SearchQuery; GO CREATE PROCEDURE dbo.DeleteNotice @ID INT ,@Password NVARCHAR(30) AS DECLARE @Count INT; SELECT @Count = COUNT(*) FROM dbo.Notice WHERE ID = @ID AND [Password] = @Password; IF @Count = 0 BEGIN Return 0; END DECLARE @ReplyCount INT; DECLARE @ReplyOrder INT; DECLARE @ReferenceID INT; DECLARE @ParentID INT; SELECT @ReplyCount = ReplyCount ,@ReplyOrder = ReplyOrder ,@ReferenceID = ReferenceID ,@ParentID = ParentID FROM dbo.Notice WHERE ID = @ID; IF @ReplyCount = 0 BEGIN IF @ReplyOrder > 0 BEGIN UPDATE dbo.Notice SET ReplyOrder = ReplyOrder - 1 WHERE ReferenceID = @ReferenceID AND ReplyOrder > @ReplyOrder; UPDATE Notice SET ReplyCount = ReplyCount - 1 WHERE ID = @ParentID; END DELETE FROM dbo.Notice WHERE ID = @ID; DELETE FROM dbo.Notice WHERE ID = @ParentID AND UpdateIP = N'((DELETED))' AND ReplyCount = 0; END ELSE BEGIN UPDATE dbo.Notice SET [Name] = N'(Unknown)', MailAddress = '', [Password] = '', Title = N'(삭제된 글입니다.)', Content = N'(삭제된 글입니다. 현재 답변이 포함되어 있기 때문에 내용만 삭제되었습니다.)', UpdateIP = N'((DELETED))', [FileName] = '', FileSize = 0, CommentCount = 0 WHERE ID = @ID; END GO CREATE PROCEDURE dbo.UpdateNotice @Name NVARCHAR(25) ,@MailAddress NVARCHAR(100) ,@Title NVARCHAR(150) ,@UpdateIP NVARCHAR(15) ,@Content NTEXT ,@Password NVARCHAR(30) ,@Encoding NVARCHAR(10) ,@Homepage NVARCHAR(100) ,@FileName NVARCHAR(255) ,@FileSize INT ,@ID INT AS DECLARE @Count INT SELECT @Count = Count(*) FROM dbo.Notice WHERE ID = @ID AND [Password] = @Password; IF @Count > 0 BEGIN UPDATE dbo.Notice SET [Name] = @Name ,MailAddress = @MailAddress ,Title = @Title ,UpdateIP = @UpdateIP ,UpdateDate = GETDATE() ,Content = @Content ,[Encoding] = @Encoding ,Homepage = @Homepage ,[FileName] = @FileName ,FileSize = @FileSize Where ID = @ID; SELECT '1'; END ELSE SELECT '0'; GO CREATE PROCEDURE dbo.SearchNotice @Page INT ,@SearchField NVARCHAR(25) ,@SearchQuery NVARCHAR(25) AS WITH OrderedNoticeBoard AS ( SELECT ID ,[Name] ,MailAddress ,Title ,WriteDate ,ReadCount ,ReferenceID ,ReplyLevel ,ReplyOrder ,ReplyCount ,ParentID ,CommentCount ,[FileName] ,FileSize ,DownloadCount ,ROW_NUMBER() OVER (ORDER BY ReferenceID DESC, ReplyOrder ASC) AS 'RowNumber' FROM dbo.Notice WHERE ( CASE @SearchField WHEN 'Name' THEN [Name] WHEN 'Title' THEN Title WHEN 'Content' THEN Content ELSE @SearchQuery END ) LIKE '%' + @SearchQuery + '%' ) SELECT ID ,[Name] ,MailAddress ,Title ,WriteDate ,ReadCount ,ReferenceID ,ReplyLevel ,ReplyOrder ,ReplyCount ,ParentID ,CommentCount ,[FileName] ,FileSize ,DownloadCount ,RowNumber FROM OrderedNoticeBoard WHERE RowNumber BETWEEN @Page * 10 + 1 AND (@Page + 1) * 10 ORDER BY ID DESC; GO |
▶ CommentControl.ascx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CommentControl.ascx.cs" Inherits="TestProject.NoticeBoard.Controls.CommentControl" %> <asp:Repeater ID="repeater" runat="server"> <HeaderTemplate> <table style="margin-left:20px;margin-right:20px;width:95%;padding:10px;"> </HeaderTemplate> <ItemTemplate> <tr style="border-bottom:1px dotted silver;"> <td style="width:80px;"><%# Eval("Name") %></td> <td style="width:350px;"><%# TestProject.HTMLHelper.Encode(Eval("Comment").ToString()) %></td> <td style="width:180px;"><%# Eval("WriteDate") %></td> <td style="width:10px;text-align:center;"> <a title="댓글 삭제" href='CommentDeletePage.aspx?NoticeID=<%= Request["ID"] %>&ID=<%# Eval("ID") %>'> <img border="0" src="/Image/NoticeBoard/delete.gif" /> </a> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> <table style="margin-left:auto;width:500px;"> <tr> <td style="width:64px;text-align:right;">성명 </td> <td style="width:128px;"> <asp:TextBox ID="nameTextBox" runat="server" CssClass="form-control" Style="display:inline-block;" Width="128px" /> </td> <td style="width:64px;text-align:right;">패스워드 </td> <td style="width:128px;"> <asp:TextBox ID="passwordTextBox" runat="server" CssClass="form-control" Style="display:inline-block;" Width="128px" TextMode="Password" /> </td> <td style="width:128px;text-align:right;"> <asp:Button ID="writeButton" runat="server" CssClass="form-control btn btn-primary" Style="display: inline-block;" Width="96px" Text="의견 남기기" OnClick="writeButton_Click" /> </td> </tr> <tr> <td style="width:64px;text-align:right;">댓글 </td> <td style="width:448px;" colspan="4"> <asp:TextBox ID="commentTextBox" runat="server" CssClass="form-control" Style="display:inline-block;" Width="448px" Rows="3" Columns="70" TextMode="MultiLine" /> </td> </tr> </table> <hr /> |
▶ CommentControl.ascx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
using System; using System.Web.UI; using NoticeBoard.Models; namespace TestProject.NoticeBoard.Controls { /// <summary> /// 댓글 컨트롤 /// </summary> public partial class CommentControl : UserControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 댓글 저장소 /// </summary> private CommentRepository repository; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - CommentControl() /// <summary> /// 생성자 /// </summary> public CommentControl() { this.repository = new CommentRepository(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { this.repeater.DataSource = this.repository.GetCommentList(Convert.ToInt32(Request["ID"])); this.repeater.DataBind(); } } #endregion #region 의견 남기기 버튼 클릭시 처리하기 - writeButton_Click(sender, e) /// <summary> /// 의견 남기기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void writeButton_Click(object sender, EventArgs e) { CommentModel comment = new CommentModel(); comment.NoticeID = Convert.ToInt32(Request["ID"]); comment.Name = this.nameTextBox.Text; comment.Password = this.passwordTextBox.Text; comment.Comment = this.commentTextBox.Text; this.repository.AddComment(comment); Response.Redirect($"{Request.ServerVariables["SCRIPT_NAME"]}?ID={Request["ID"]}"); } #endregion } } |
▶ EditorControl.ascx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="EditorControl.ascx.cs" Inherits="TestProject.NoticeBoard.Controls.EditorControl" %> <style> .BoardWriteFormTableLeftStyle { width : 100px; text-align : right; } </style> <h2 style="text-align:center;">게시판</h2> <asp:Label ID="titleDescriptionLabel" runat="server" ForeColor="#ff0000" /> <hr /> <table style="margin-left:auto;margin-right:auto;width:600px;border-collapse:collapse;padding:5px;"> <% if(!string.IsNullOrEmpty(Request.QueryString["ID"]) && FormType == NoticeBoard.Models.BoardWriteFormType.Modify) { %> <tr> <td class="BoardWriteFormTableLeftStyle"> <span style="color: #ff0000;">*</span>ID </td> <td style="width:500px;"> <%= Request.QueryString["ID"] %> </td> </tr> <% } %> <tr> <td class="BoardWriteFormTableLeftStyle"><span style="color: #ff0000;">*</span>성명</td> <td style="width:500px;"> <asp:TextBox ID="nameTextBox" runat="server" CssClass="form-control" MaxLength="10" Width="150px" /> <asp:RequiredFieldValidator ID="nameRequiredFieldValidator" runat="server" ControlToValidate="nameTextBox" Display="None" SetFocusOnError="True" ErrorMessage="* 성명을 입력해 주시기 바랍니다." /> </td> </tr> <tr> <td style="text-align:right;">메일 주소</td> <td> <asp:TextBox ID="mailAddressTextBox" runat="server" CssClass="form-control" style="display:inline-block;" MaxLength="80" Width="200px" /> <span style="color:#aaaaaa;font-style:italic">(선택 사항)</span> <asp:RegularExpressionValidator ID="mailAddressRegularExpressionValidator" runat="server" ControlToValidate="mailAddressTextBox" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" Display="None" SetFocusOnError="True" ErrorMessage="* 메일 주소를 입력해 주시기 바랍니다." /> </td> </tr> <tr> <td style="text-align:right;">홈페이지</td> <td> <asp:TextBox ID="homepageTextBox" runat="server" CssClass="form-control" style="display:inline-block;" MaxLength="80" Width="300px" /> <span style="color:#aaaaaa;font-style:italic;">(선택 사항)</span> <asp:RegularExpressionValidator ID="homepageRegularExpressionValidator" runat="server" ControlToValidate="homepageTextBox" ValidationExpression="http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?" Display="None" SetFocusOnError="True" ErrorMessage="* 홈페이지를 입력해 주시기 바랍니다." /> </td> </tr> <tr> <td style="text-align:right;"><span style="color: #ff0000;">*</span>제목</td> <td> <asp:TextBox ID="titleTextBox" runat="server" CssClass="form-control" Width="480px"></asp:TextBox> <asp:RequiredFieldValidator ID="titleRequiredFieldValidator" runat="server" ControlToValidate="titleTextBox" Display="None" SetFocusOnError="True" ErrorMessage="* 제목을 입력해 주시기 바랍니다." /> </td> </tr> <tr> <td style="text-align:right;"><span style="color: #ff0000;">*</span>내용</td> <td> <asp:TextBox ID="contentTextBox" runat="server" CssClass="form-control" style="display:inline-block;" Width="480px" Height="150px" TextMode="MultiLine" /> <asp:RequiredFieldValidator ID="contentRequiredFieldValidator" runat="server" ControlToValidate="contentTextBox" Display="None" SetFocusOnError="True" ErrorMessage="* 내용을 입력해 주시기 바랍니다." /> </td> </tr> <tr> <td style="text-align:right;">파일 첨부</td> <td> <asp:CheckBox ID="uploadCheckBox" runat="server" CssClass="check-inline" AutoPostBack="True" Text="체크 박스를 체크하면 업로드 화면이 표시됩니다." OnCheckedChanged="uploadCheckBox_CheckedChanged" /> <span style="color:#aaaaaa;font-style:italic">(선택 사항)</span> <br /> <asp:Panel ID="filePanel" runat="server" Width="480px" Height="25px" Visible="false"> <input id="fileNameButton" runat="server" style="width:290px;height:22px" name="fileNameTextBox" type="file" /> <asp:label ID="previousFileNameLabel" runat="server" text="" Visible="false" /> </asp:Panel> </td> </tr> <tr> <td style="text-align:right;"><span style="color: #ff0000;">*</span>인코딩</td> <td> <asp:RadioButtonList ID="encodingRadioButtonList" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow"> <asp:ListItem Value="Text" Selected="True">텍스트</asp:ListItem> <asp:ListItem Value="HTML">HTML</asp:ListItem> <asp:ListItem Value="Mixed">혼합</asp:ListItem> </asp:RadioButtonList> </td> </tr> <tr> <td style="text-align:right;"><span style="color: #ff0000;">*</span>패스워드</td> <td> <asp:TextBox ID="passwordTextBox" runat="server" CssClass="form-control" style="display:inline-block;" MaxLength="20" Width="150px" TextMode="Password" EnableViewState="False" /> <span style=" color: #aaaaaa;">(수정/삭제시 필요)</span> <asp:RequiredFieldValidator ID="passwordRequiredFieldValidator" runat="server" ControlToValidate="passwordTextBox" Display="None" SetFocusOnError="True" ErrorMessage="* 패스워드를 입력해 주시기 바랍니다." /> </td> </tr> <% if(!Page.User.Identity.IsAuthenticated) { %> <tr> <td style="text-align:right;"><span style="color: #ff0000;">*</span>보안코드</td> <td> <asp:TextBox ID="imageTextTextBox" runat="server" CssClass="form-control" style="display:inline-block;" MaxLength="20" Width="150px" EnableViewState="False" /> <span style=" color: #aaaaaa;">(아래에 제시되는 보안코드를 입력하십시오.)</span> <br /> <asp:Image ID="imageTextImage" runat="server" ImageUrl="~/NoticeBoard/ImageTextPage.aspx" /> <asp:Label ID="errorLabel" runat="server" ForeColor="Red" /> </td> </tr> <% } %> <tr> <td colspan="2" style="text-align:center;"> <asp:Button ID="saveButton" runat="server" CssClass="btn btn-primary" Text="저장" OnClick="saveButton_Click" /> <a class="btn btn-default" href="NoticeListPage.aspx">목록</a> <br /> <asp:ValidationSummary ID="validationSummary" runat="server" ShowSummary="False" ShowMessageBox="True" DisplayMode="List" /> <br /> </td> </tr> </table> |
▶ EditorControl.ascx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
using System; using System.IO; using System.Web.UI; using NoticeBoard.Models; namespace TestProject.NoticeBoard.Controls { /// <summary> /// 에디터 컨트롤 /// </summary> public partial class EditorControl : UserControl { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// ID /// </summary> private string id; /// <summary> /// 업로드 디렉토리 경로 /// </summary> private string uploadDirectoryPath = string.Empty; /// <summary> /// 파일명 /// </summary> private string fileName = string.Empty; /// <summary> /// 파일 크기 /// </summary> private int fileSize = 0; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 폼 타입 - FormType /// <summary> /// 폼 타입 /// </summary> public BoardWriteFormType FormType { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { this.id = Request.QueryString["ID"]; if(!Page.IsPostBack) { switch(FormType) { case BoardWriteFormType.Write : this.titleDescriptionLabel.Text = "글 쓰기 - 아래 항목을 입력해 주시기 바랍니다."; break; case BoardWriteFormType.Modify : this.titleDescriptionLabel.Text = "글 수정 - 아래 항목을 입력해 주시기 바랍니다."; DisplayDataForUpdate(); break; case BoardWriteFormType.Reply : this.titleDescriptionLabel.Text = "글 답변 - 아래 항목을 입력해 주시기 바랍니다."; DisplayDataForReply(); break; } } } #endregion #region 업로드 체크 박스 체크 변경시 처리하기 - uploadCheckBox_CheckedChanged(sender, e) /// <summary> /// 업로드 체크 박스 체크 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void uploadCheckBox_CheckedChanged(object sender, EventArgs e) { this.filePanel.Visible = !this.filePanel.Visible; } #endregion #region 저장 버튼 클릭시 처리하기 - saveButton_Click(object sender, EventArgs e) /// <summary> /// 저장 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void saveButton_Click(object sender, EventArgs e) { if(ValidateSecurtyImageText()) { UploadFile(); NoticeModel notice = new NoticeModel(); notice.ID = Convert.ToInt32(this.id); notice.Name = this.nameTextBox.Text; notice.MailAddress = HTMLHelper.Encode(this.mailAddressTextBox.Text); notice.Homepage = this.homepageTextBox.Text; notice.Title = HTMLHelper.Encode(this.titleTextBox.Text); notice.Content = this.contentTextBox.Text; notice.FileName = this.fileName; notice.FileSize = this.fileSize; notice.Password = this.passwordTextBox.Text; notice.WriteIP = Request.UserHostAddress; notice.Encoding = this.encodingRadioButtonList.SelectedValue; NoticeRepository repository = new NoticeRepository(); switch(FormType) { case BoardWriteFormType.Write : repository.Add(notice); Response.Redirect("NoticeListPage.aspx"); break; case BoardWriteFormType.Modify : notice.UpdateIP = Request.UserHostAddress; notice.FileName = ViewState["FileName"].ToString(); notice.FileSize = Convert.ToInt32(ViewState["FileSize"]); int recordCount = repository.Update(notice); if(recordCount > 0) { Response.Redirect($"NoticeViewPage.aspx?ID={this.id}"); } else { this.errorLabel.Text = "수정을 실패했습니다. 암호를 확인해 주시기 바랍니다."; } break; case BoardWriteFormType.Reply : notice.ParentID = Convert.ToInt32(this.id); repository.Reply(notice); Response.Redirect("NoticeListPage.aspx"); break; default : repository.Add(notice); Response.Redirect("NoticeListPage.aspx"); break; } } else { this.errorLabel.Text = "보안코드가 일치하지 않습니다.. 다시 입력해 주시기 바랍니다."; } } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 수정용 데이터 표시하기 - DisplayDataForUpdate() /// <summary> /// 수정용 데이터 표시하기 /// </summary> private void DisplayDataForUpdate() { NoticeModel notice = (new NoticeRepository()).Get(Convert.ToInt32(this.id)); this.nameTextBox.Text = notice.Name; this.mailAddressTextBox.Text = notice.MailAddress; this.homepageTextBox.Text = notice.Homepage; this.titleTextBox.Text = notice.Title; this.contentTextBox.Text = notice.Content; string ecoding = notice.Encoding; if(ecoding == "Text") { this.encodingRadioButtonList.SelectedIndex = 0; } else if(ecoding == "Mixed") { this.encodingRadioButtonList.SelectedIndex = 2; } else { this.encodingRadioButtonList.SelectedIndex = 1; } if(notice.FileName.Length > 1) { ViewState["FileName"] = notice.FileName; ViewState["FileSize"] = notice.FileSize; this.filePanel.Height = 50; this.previousFileNameLabel.Visible = true; this.previousFileNameLabel.Text = $"기존 업로드 파일명 : {notice.FileName}"; } else { ViewState["FileName"] = ""; ViewState["FileSize"] = 0; } } #endregion #region 답변용 데이터 표시하기 - DisplayDataForReply() /// <summary> /// 답변용 데이터 표시하기 /// </summary> private void DisplayDataForReply() { NoticeModel notice = (new NoticeRepository()).Get(Convert.ToInt32(this.id)); this.titleTextBox.Text = $"Re : {notice.Title}"; this.contentTextBox.Text = $"\n\nOn {notice.WriteDate}, '{notice.Name}' wrote:\n----------\n>{notice.Content.Replace("\n", "\n>")}\n---------"; } #endregion #region 보안 이미지 텍스트 검증하기 - ValidateSecurtyImageText() /// <summary> /// 보안 이미지 텍스트 검증하기 /// </summary> private bool ValidateSecurtyImageText() { if(Page.User.Identity.IsAuthenticated) { return true; } else { if(Session["ImageText"] != null) { return (this.imageTextTextBox.Text == Session["ImageText"].ToString()); } } return false; } #endregion #region 파일 업로드하기 - UploadFile() /// <summary> /// 파일 업로드하기 /// </summary> private void UploadFile() { this.uploadDirectoryPath = Server.MapPath("~/FileUpload"); this.fileName = string.Empty; this.fileSize = 0; if(this.fileNameButton.PostedFile != null) { if(this.fileNameButton.PostedFile.FileName.Trim().Length > 0 && this.fileNameButton.PostedFile.ContentLength > 0) { if(FormType == BoardWriteFormType.Modify) { ViewState["FileName"] = FileHelper.GetUniqueFileName ( this.uploadDirectoryPath, Path.GetFileName(this.fileNameButton.PostedFile.FileName) ); ViewState["FileSize"] = this.fileNameButton.PostedFile.ContentLength; this.fileNameButton.PostedFile.SaveAs ( Path.Combine ( this.uploadDirectoryPath, ViewState["FileName"].ToString() ) ); } else { this.fileName = FileHelper.GetUniqueFileName ( this.uploadDirectoryPath, Path.GetFileName(this.fileNameButton.PostedFile.FileName) ); this.fileSize = this.fileNameButton.PostedFile.ContentLength; this.fileNameButton.PostedFile.SaveAs(Path.Combine(this.uploadDirectoryPath, this.fileName)); } } } } #endregion } } |
▶
■ FormsAuthentication 클래스를 사용해 사용자 로그인을 관리하는 방법을 보여준다. ▶ TestDB.sql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
CREATE TABLE dbo.[User] ( ID INT NOT NULL IDENTITY(1, 1) PRIMARY KEY ,UserID NVARCHAR(50) NOT NULL ,[Password] NVARCHAR(50) NOT NULL ); GO CREATE PROCEDURE dbo.WriteUser @UserID NVARCHAR(25) ,@Password NVARCHAR(20) As INSERT INTO dbo.[User] VALUES (@UserID, @Password); GO CREATE PROCEDURE dbo.ListUser AS SELECT ID ,UserID ,[Password] FROM dbo.[User] ORDER BY ID DESC; GO CREATE PROCEDURE dbo.ViewUser @ID INT AS SELECT ID ,UserID ,[Password] From dbo.[User] WHERE ID = @ID; GO CREATE PROCEDURE dbo.UpdateUser @UserID NVARCHAR(50) ,@Password NVARCHAR(50) ,@ID INT AS BEGIN TRANSACTION; UPDATE dbo.[User] SET UserID = @UserID, [Password] = @Password WHERE ID = @ID; COMMIT TRANSACTION; GO CREATE PROCEDURE dbo.DeleteUser @ID INT AS DELETE dbo.[User] WHERE ID = @ID; GO CREATE PROCEDURE dbo.SearchUser @SearchField NVARCHAR(100) ,@SearchQuery NVARCHAR(100) AS DECLARE @SQL NVARCHAR(1000) SET @SQL = ' SELECT * FROM dbo.[User] WHERE ' + @SearchField + ' LIKE ''%' + @SearchQuery + '%'' ' EXECUTE SP_EXECUTESQL @SQL; GO |
▶ UserModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
namespace TestProject.Models { /// <summary> /// 사용자 모델 /// </summary> public class UserModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 사용자 ID - UserID /// <summary> /// 사용자 ID /// </summary> public string UserID { get; set; } #endregion #region 패스워드 - Password /// <summary> /// 패스워드 /// </summary> public string Password { get; set; } #endregion } } |
▶ UserRepository.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
using System.Data; using System.Data.SqlClient; using System.Web.Configuration; using TestProject.Models; namespace TestProject { /// <summary> /// 사용자 저장소 /// </summary> public class UserRepository { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// SQL 연결 /// </summary> private SqlConnection connection; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - UserRepository() /// <summary> /// 생성자 /// </summary> public UserRepository() { this.connection = new SqlConnection(); this.connection.ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 사용자 추가하기 - AddUser(userID, password) /// <summary> /// 사용자 추가하기 /// </summary> /// <param name="userID">사용자 ID</param> /// <param name="password">패스워드</param> public void AddUser(string userID, string password) { SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "WriteUser"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@UserID" , userID ); command.Parameters.AddWithValue("@Password", password); this.connection.Open(); command.ExecuteNonQuery(); this.connection.Close(); } #endregion #region 사용자 구하기 - GetUser(userID) /// <summary> /// 사용자 구하기 /// </summary> /// <param name="userID">사용자 ID</param> /// <returns>사용자</returns> public UserModel GetUser(string userID) { UserModel user = new UserModel(); SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "SELECT * FROM dbo.[User] WHERE UserID = @UserID"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@UserID", userID); this.connection.Open(); IDataReader reader = command.ExecuteReader(); if(reader.Read()) { user.ID = reader.GetInt32(0); user.UserID = reader.GetString(1); user.Password = reader.GetString(2); } this.connection.Close(); return user; } #endregion #region 사용자 수정하기 - UpdateUser(id, userID, password) /// <summary> /// 사용자 수정하기 /// </summary> /// <param name="id">ID</param> /// <param name="userID">사용자 ID</param> /// <param name="password">패스워드</param> public void UpdateUser(int id, string userID, string password) { SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "UpdateUser"; command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@UserID" , userID ); command.Parameters.AddWithValue("@Password", password); command.Parameters.AddWithValue("@ID" , id ); this.connection.Open(); command.ExecuteNonQuery(); this.connection.Close(); } #endregion #region 검증된 사용자 여부 구하기 - IsValidUser(userID, password) /// <summary> /// 검증된 사용자 여부 구하기 /// </summary> /// <param name="userID">사용자 ID</param> /// <param name="password">패스워드</param> /// <returns>검증된 사용자 여부</returns> public bool IsValidUser(string userID, string password) { bool result = false; this.connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = this.connection; command.CommandText = "SELECT * FROM dbo.[User] WHERE UserID = @UserID AND Password = @Password"; command.CommandType = CommandType.Text; command.Parameters.AddWithValue("@UserID" , userID ); command.Parameters.AddWithValue("@Password", password); SqlDataReader reader = command.ExecuteReader(); if(reader.Read()) { result = true; } reader.Close(); this.connection.Close(); return result; } #endregion } } |
▶ Web.config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation targetFramework="4.6" debug="true" /> <httpRuntime targetFramework="4.6" /> <authentication mode="Forms"> <forms loginUrl="~/LoginPage.aspx" /> </authentication> </system.web> <connectionStrings> <add name="ConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> |
▶
■ Chart 클래스를 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <%@ Register TagPrefix="asp" Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Chart 클래스 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <h3>선언적 방식</h3> <asp:Chart ID="chart1" runat="server"> <Series> <asp:Series Name="series1" ChartType="Column" YValuesPerPoint="2"> <Points> <asp:DataPoint AxisLabel="국어" YValues="90 ,0" /> <asp:DataPoint AxisLabel="영어" YValues="100,0" /> <asp:DataPoint AxisLabel="수학" YValues="95 ,0" /> </Points> </asp:Series> </Series> <ChartAreas> <asp:ChartArea Name="chartArea1" /> </ChartAreas> </asp:Chart> <hr /> <h3>프로그래밍 방식</h3> <asp:Chart ID="chart2" runat="server"> <Series> <asp:Series Name="series1" /> </Series> <ChartAreas> <asp:ChartArea Name="chartArea1" /> </ChartAreas> </asp:Chart> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
using System; using System.Web.UI; using System.Web.UI.DataVisualization.Charting; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { DisplayChart(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 차트 표시하기 - DisplayChart() /// <summary> /// 차트 표시하기 /// </summary> private void DisplayChart() { this.chart2.Series[0].ChartType = SeriesChartType.Column; this.chart2.Series[0].Points.AddXY("국어", 90 ); this.chart2.Series[0].Points.AddXY("영어", 100); this.chart2.Series[0].Points.AddXY("수학", 95 ); } #endregion } } |
TestProject.zip
■ ObjectDataSource 클래스를 사용하는 방법을 보여준다. ▶ TestDB.sql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
CREATE TABLE dbo.Memo ( ID INT IDENTITY(1, 1) PRIMARY KEY, -- ID Title NVARCHAR(100) NOT NULL, -- 제목 MailAddress NVARCHAR(100) NULL, -- 메일 주소 [Description] NVARCHAR(500) NOT NULL, -- 설명 WriteDate DATETIME DEFAULT(GETDATE()), -- 작성일 WriteIP NVARCHAR(15) NULL -- 작성 IP 주소 ) GO INSERT INTO dbo.Memo VALUES ( N'메모1', N'test@daum.com', N'테스트 문자열1', GetDate(), '127.0.0.1' ) Go INSERT INTO dbo.Memo VALUES ( N'메모2', N'test@daum.com', N'테스트 문자열2', GetDate(), '127.0.0.1' ) Go CREATE PROCEDURE dbo.ListMemo AS SELECT ID ,Title ,MailAddress ,[Description] ,WriteDate ,WriteIP FROM dbo.Memo ORDER BY ID DESC GO |
▶ Web.config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation targetFramework="4.6" debug="true" /> <httpRuntime targetFramework="4.6" /> </system.web> <connectionStrings> <add name="ConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True;" /> </connectionStrings> </configuration> |
▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ObjectDataSource 클래스 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:GridView ID="gridView" runat="server" DataSourceID="objectDataSource" /> <asp:ObjectDataSource ID="objectDataSource" runat="server" SelectMethod="GetDataReader" TypeName="TestProject.MainPage" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 데이터 리더 구하기 - GetDataReader() /// <summary> /// 데이터 리더 구하기 /// </summary> /// <returns>데이터 리더</returns> public SqlDataReader GetDataReader() { SqlConnection connection = new SqlConnection(); connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "ListMemo"; command.CommandType = CommandType.StoredProcedure; return command.ExecuteReader(CommandBehavior.CloseConnection); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ XmlDataSource 클래스를 사용하는 방법을 보여준다. ▶ MainPage.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version="1.0" encoding="utf-8" ?> <Interests> <Interest> <title>Windows Server</title> <description>Best Operation System</description> </Interest> <Interest> <title>SQL Server</title> <description>Nice DataBase Management System</description> </Interest> <Interest> <title>C#</title> <description>Cool Programming Language</description> </Interest> <Interest> <title>ASP.NET</title> <description>Perfect Web Application Framework</description> </Interest> </Interests> |
▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>XmlDataSource 클래스 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:DataList ID="dataList" runat="server" DataSourceID="xmlDataSource"> <ItemTemplate> <em><%# XPath("title") %></em>: <%# XPath("description") %> </ItemTemplate> </asp:DataList> <asp:XmlDataSource ID="xmlDataSource" runat="server" DataFile="~/MainPage.xml"> </asp:XmlDataSource> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ DAPPER CRUD 작업을 하는 방법을 보여준다. ▶ TestDB.sql
1 2 3 4 5 6 7 8 9 10 11 |
CREATE TABLE dbo.Maxims ( ID INT NOT NULL IDENTITY(1, 1) ,[Name] NVARCHAR(100) NOT NULL ,Content NVARCHAR(500) NOT NULL ,CreateDate DATETIME NULL DEFAULT(GETDATE()) PRIMARY KEY CLUSTERED (ID ASC) ) GO |
▶ Maxims.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; namespace TestProject.Models { /// <summary> /// 격언 /// </summary> public class Maxims { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 명칭 - Name /// <summary> /// 명칭 /// </summary> public string Name { get; set; } #endregion #region 내용 - Content /// <summary> /// 내용 /// </summary> public string Content { get; set; } #endregion #region 생성일 - CreateDate /// <summary> /// 생성일 /// </summary> public DateTime CreateDate { get; set; } #endregion } } |
▶ MaximsServiceRegistory.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using Dapper; using TestProject.Models; namespace TestProject { /// <summary> /// 격언 서비스 저장소 /// </summary> public class MaximServiceRepository { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// DB 연결 /// </summary> private IDbConnection connection = new SqlConnection ( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString ); #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 리스트 구하기 - GetList() /// <summary> /// 리스트 구하기 /// </summary> /// <returns>리스트</returns> public List<Maxims> GetList() { string sql = "SELECT ID, [Name], Content, CreateDate FROM dbo.Maxims ORDER BY ID ASC"; return this.connection.Query<Maxims>(sql).ToList(); } #endregion #region 구하기 - Get(id) /// <summary> /// 구하기 /// </summary> /// <param name="id">ID</param> /// <returns>격언</returns> public Maxims Get(int id) { string sql = "SELECT ID, [Name], Content, CreateDate FROM dbo.Maxims WHERE ID = @ID"; return this.connection.Query<Maxims>(sql, new { ID = id }).SingleOrDefault(); } #endregion #region 추가하기 - Add(maxims) /// <summary> /// 추가하기 /// </summary> /// <param name="maxims">격언</param> /// <returns>격언</returns> public Maxims Add(Maxims maxims) { string sql = @" Insert Into dbo.Maxims ( [Name] ,Content ) Values ( @Name, @Content ); Select Cast(SCOPE_IDENTITY() As Int); "; var id = this.connection.Query<int>(sql, maxims).Single(); maxims.ID = id; return maxims; } #endregion #region 수정하기 - Update(maxims) /// <summary> /// 수정하기 /// </summary> /// <param name="maxims">격언</param> /// <returns>격언</returns> public Maxims Update(Maxims maxims) { string sql = "UPDATE dbo.Maxims SET [Name] = @Name, Content = @Content WHERE ID = @ID"; this.connection.Execute(sql, maxims); return maxims; } #endregion #region 삭제하기 - Delete(id) /// <summary> /// 삭제하기 /// </summary> /// <param name="id">ID</param> public void Delete(int id) { string sql = "DELETE FROM dbo.Maxims WHERE ID = @ID"; this.connection.Execute(sql, new { ID = id }); } #endregion } } |
▶ Web.config
1 2 3 4 5 6 7 8 9 10 11 |
<?xml version="1.0"?> <configuration> <system.web> <compilation targetFramework="4.6.1" debug="true" /> </system.web> <connectionStrings> <add name="ConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True" /> </connectionStrings> </configuration> |
▶ ListPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListPage.aspx.cs" Inherits="TestProject.ListPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>DAPPER CRUD 작업하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:GridView ID="gridView" runat="server"> <Columns> <asp:HyperLinkField Text="상세보기" DataNavigateUrlFormatString="~/ViewPage.aspx?ID={0}" DataNavigateUrlFields="ID" /> </Columns> </asp:GridView> <hr /> <asp:HyperLink ID="writeHyperLink" runat="server" NavigateUrl="~/WritePage.aspx"> 쓰기 </asp:HyperLink> </div> </form> </body> </html> |
■ 데이터베이스 CRUD 작업하는 방법을 보여준다. ▶ TestDB.sql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
CREATE TABLE dbo.Memo ( ID INT IDENTITY(1, 1) PRIMARY KEY, -- ID Title NVARCHAR(100) NOT NULL, -- 제목 MailAddress NVARCHAR(100) NULL, -- 메일 주소 [Description] NVARCHAR(500) NOT NULL, -- 설명 WriteDate DATETIME DEFAULT(GETDATE()), -- 작성일 WriteIP NVARCHAR(15) NULL -- 작성 IP 주소 ) GO INSERT INTO dbo.Memo VALUES ( N'메모1', N'test@daum.com', N'테스트 문자열', GetDate(), '127.0.0.1' ) Go SELECT ID ,Title ,MailAddress ,[Description] ,WriteDate ,WriteIP FROM dbo.Memo ORDER BY ID DESC GO SELECT ID ,Title ,MailAddress ,[Description] ,WriteDate ,WriteIP FROM dbo.Memo WHERE ID = 1 GO BEGIN TRANSACTION UPDATE dbo.Memo SET Title = N'메모1 (수정)', MailAddress = N'test@daum.com', [Description] = N'테스트 문자열 (수정)', WriteIP = N'127.0.0.1' Where ID = 1 COMMIT TRANSACTION GO BEGIN TRANSACTION DELETE FROM dbo.Memo Where ID = 10 COMMIT TRAN GO SELECT ID ,Title ,MailAddress ,[Description] ,WriteDate ,WriteIP From dbo.Memo Where Title = '메모1' Or MailAddress Like '%test%' ORDER BY ID DESC GO CREATE PROCEDURE dbo.WriteMemo(@Title NVARCHAR(100), @MailAddress NVARCHAR(100), @Description NVARCHAR(500), @WriteIP NVARCHAR(15)) AS INSERT INTO dbo.Memo ( Title ,MailAddress ,[Description] ,WriteIP ) Values ( @Title ,@MailAddress ,@Description ,@WriteIP ) GO CREATE PROCEDURE dbo.ListMemo AS SELECT ID ,Title ,MailAddress ,[Description] ,WriteDate ,WriteIP FROM dbo.Memo ORDER BY ID DESC GO CREATE PROCEDURE dbo.ViewMemo(@ID INT) AS SELECT ID ,Title ,MailAddress ,[Description] ,WriteDate ,WriteIP FROM dbo.Memo WHERE ID = @ID GO CREATE PROCEDURE dbo.UpdateMemo(@Title NVARCHAR(100), @MailAddress NVARCHAR(100), @Description NVARCHAR(150), @ID INT) AS BEGIN TRANSACTION UPDATE dbo.Memo SET Title = @Title ,MailAddress = @MailAddress ,[Description] = @Description Where ID = @ID COMMIT TRANSACTION GO CREATE PROCEDURE dbo.DeleteMemo(@ID INT) AS DELETE FROM dbo.Memo Where ID = @ID GO CREATE PROCEDURE dbo.SearchMemo(@SearchField NVARCHAR(100), @SearchQuery NVARCHAR(100)) AS DECLARE @SQL NVARCHAR(1000) SET @SQL = ' SELECT ID ,Title ,MailAddress ,[Description] ,WriteDate ,WriteIP FROM dbo.Memo WHERE ' + @SearchField + ' LIKE N''%' + @SearchQuery + '%'' ORDER BY ID DESC ' EXECUTE SP_EXECUTESQL @SQL GO |
▶ MemoModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
using System; namespace TestProject.Models { /// <summary> /// 메모 모델 /// </summary> public class MemoModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제목 - Title /// <summary> /// 제목 /// </summary> public string Title { get; set; } #endregion #region 메일 주소 - MailAddress /// <summary> /// 메일 주소 /// </summary> public string MailAddress { get; set; } #endregion #region 설명 - Description /// <summary> /// 설명 /// </summary> public string Description { get; set; } #endregion #region 작성일 - WriteDate /// <summary> /// 작성일 /// </summary> public DateTime WriteDate { get; set; } #endregion #region 작성 IP - WriteIP /// <summary> /// 작성 IP /// </summary> public string WriteIP { get; set; } #endregion } } |
▶ Web.config
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation targetFramework="4.6" debug="true" /> <httpRuntime targetFramework="4.6" /> </system.web> <connectionStrings> <add name="ConnectionString" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=TestDB;Integrated Security=True;" /> </connectionStrings> </configuration> |
▶ ListPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListPage.aspx.cs" Inherits="TestProject.ListPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>데이터베이스 CRUD 작업하기</title> </head> <body> <form id="form" runat="server"> <div> <h3>메모 목록</h3> <asp:GridView ID="gridView" runat="server" AutoGenerateColumns="false"> <Columns> <asp:BoundField HeaderText="ID" DataField="ID" /> <asp:BoundField HeaderText="Title" DataField="Title" /> <asp:HyperLinkField HeaderText="설명" DataTextField="Description" DataNavigateUrlFormatString="ViewPage.aspx?ID={0}" DataNavigateUrlFields="ID" /> <asp:TemplateField HeaderText="작성일"> <ItemTemplate> <%# Eval("WriteDate") %> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <hr /> <asp:HyperLink ID="writeHyperLink" runat="server" NavigateUrl="~/WritePage.aspx"> 쓰기 </asp:HyperLink> <asp:HyperLink ID="searchHyperLink" runat="server" NavigateUrl="~/SearchPage.aspx"> 검색 </asp:HyperLink> </div> </form> </body> </html> |
▶ ListPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Web.UI; namespace TestProject { /// <summary> /// 목록 페이지 /// </summary> public partial class ListPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlCommand command = new SqlCommand("ListMemo", connection); command.CommandType = CommandType.StoredProcedure; SqlDataAdapter adapter = new SqlDataAdapter(command); DataSet dataSet = new DataSet(); adapter.Fill(dataSet, "Memo"); this.gridView.DataSource = dataSet; this.gridView.DataBind(); connection.Close(); } #endregion } } |
▶
■ Page 클래스의 Session 속성을 사용해 일정 시간 내 글쓰기를 방지하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Page 클래스 : Session 속성을 사용해 일정 시간 내 글쓰기 방지하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:TextBox ID="inputTextBox" runat="server" /> <asp:Button ID="writeButton" runat="server" Text="글 쓰기" OnClick="writeButton_Click" /> <asp:Label ID="displayLabel" runat="server" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion #region 글 쓰기 버튼 클릭시 처리하기 - writeButton_Click(sender, e) /// <summary> /// 글 쓰기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void writeButton_Click(object sender, EventArgs e) { if(Session["WriteTime"] != null) { DateTime writeTime = Convert.ToDateTime(Session["WriteTime"]); TimeSpan timeSpan = DateTime.Now - writeTime; if(timeSpan.TotalSeconds < 5) { this.displayLabel.Text = "잠시 대기해 주시기 바랍니다."; return; } } Session["WriteTime"] = DateTime.Now; this.displayLabel.Text = this.inputTextBox.Text; } #endregion } } |
TestProject.zip
■ ASP.NET 상태를 관리하는 방법을 보여준다. ▶ Global.asax.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Web; namespace TestProject { /// <summary> /// 글로벌 /// </summary> public class Global : HttpApplication { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 애플리케이션 시작시 처리하기 - Application_Start(sender, e) /// <summary> /// 애플리케이션 시작시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Application_Start(object sender, EventArgs e) { Application["Now"] = DateTime.Now; } #endregion #region 세션 시작시 처리하기 - Session_Start(sender, e) /// <summary> /// 세션 시작시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Session_Start(object sender, EventArgs e) { Session["Now"] = DateTime.Now; } #endregion } } |
▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ASP.NET 상태 관리하기</title> </head> <body> <form id="form" runat="server"> <div> <h3>서버 저장</h3> Application : <asp:TextBox ID="applicationTextBox" runat="server" /><br /> Session : <asp:TextBox ID="sessionTextBox" runat="server" /><br /> Cache : <asp:TextBox ID="cacheTextBox" runat="server" /><br /> <h3>클라이언트 저장</h3> Cookie : <asp:TextBox ID="cookieTextBox" runat="server" /><br /> ViewState : <asp:TextBox ID="viewStateTextBox" runat="server" /> <hr /> <asp:LinkButton ID="saveButton" runat="server" OnClick="saveButton_Click"> 상태 변수 데이터 저장 </asp:LinkButton> <asp:LinkButton ID="postbackButton" runat="server"> 다시 게시 </asp:LinkButton> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { this.applicationTextBox.Text = Application["Now"].ToString(); this.sessionTextBox.Text = Session["Now"].ToString(); if(Cache["Now"] != null) { this.cacheTextBox.Text = Cache["Now"].ToString(); } if(Request.Cookies["Now"] != null) { this.cookieTextBox.Text = Server.UrlDecode(Request.Cookies["Now"].Value); } if(ViewState["Now"] != null) { this.viewStateTextBox.Text = ViewState["Now"].ToString(); } } } #endregion #region 저장 버튼 클릭시 처리하기 - saveButton_Click(sender, e) /// <summary> /// 저장 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void saveButton_Click(object sender, EventArgs e) { Application["Now"] = this.applicationTextBox.Text; Session["Now"] = this.sessionTextBox.Text; Cache["Now"] = this.cacheTextBox.Text; Response.Cookies["Now"].Value = Server.UrlEncode(this.cookieTextBox.Text); ViewState["Now"] = this.viewStateTextBox.Text; Response.Redirect("StatePage.aspx"); } #endregion } } |
▶ StatePage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StatePage.aspx.cs" Inherits="TestProject.StatePage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>저장 상태 조회</title> </head> <body> <form id="form" runat="server"> <div> <h3>서버 저장</h3> Application : <asp:TextBox ID="applicationTextBox" runat="server" /><br /> Session : <asp:TextBox ID="sessionTextBox" runat="server" /><br /> Cache : <asp:TextBox ID="cacheTextBox" runat="server" /><br /> <h3>클라이언트 저장</h3> Cookies : <asp:TextBox ID="cookieTextBox" runat="server" /><br /> ViewState : <asp:TextBox ID="viewStateTextBox" runat="server" /> </div> </form> </body> </html> |
▶ StatePage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 상태 페이지 /// </summary> public partial class StatePage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { this.applicationTextBox.Text = Application["Now"].ToString(); this.sessionTextBox.Text = Session["Now"].ToString(); if(Cache["Now"] != null) { this.cacheTextBox.Text = Cache["Now"].ToString(); } if(Request.Cookies["Now"] != null) { this.cookieTextBox.Text = Server.UrlDecode(Request.Cookies["Now"].Value); } if(ViewState["Now"] != null) { this.viewStateTextBox.Text = ViewState["Now"].ToString(); } } #endregion } } |
TestProject.zip
■ MasterPage 클래스에서 마스터 페이지를 사용하는 방법을 보여준다. ▶ Site.css
1 2 3 4 5 6 7 8 9 10 11 12 13 |
body { padding-top : 50px; padding-bottom : 20px; } .body-content { padding-left : 15px; padding-right : 15px; } |
▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<%@ Page Title="MasterPage 클래스 : 마스터 페이지 사용하기" Language="C#" MasterPageFile="~/MainMasterPage.Master" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeaderContent" runat="server" /> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <div class="jumbotron"> <h1>메인 페이지</h1> <p>마스터 페이지, 레이아웃 페이지 등의 표현 방법은 웹 사이트 공통 레이아웃을 정의하는 기능입니다.</p> </div> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="FooterContent" runat="server" /> |
▶ AboutPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<%@ Page Title="정보 페이지" Language="C#" MasterPageFile="~/MainMasterPage.Master" AutoEventWireup="true" CodeBehind="AboutPage.aspx.cs" Inherits="TestProject.AboutPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeaderContent" runat="server" /> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>정보 페이지</h2> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="FooterContent" runat="server" /> |
▶ ContactPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<%@ Page Title="연락처 페이지" Language="C#" MasterPageFile="~/MainMasterPage.Master" AutoEventWireup="true" CodeBehind="ContactPage.aspx.cs" Inherits="TestProject.ContactPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="HeaderContent" runat="server" /> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>연락처 페이지</h2> </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="FooterContent" runat="server" /> |
▶ MainMasterPage.Master
■ UserControl 클래스를 사용해 웹 사이트 뼈대를 만드는 방법을 보여준다. ▶ NavigatorUserControl.ascx
1 2 3 4 5 6 7 8 |
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="NavigatorUserControl.ascx.cs" Inherits="TestProject.NavigatorUserControl" %> <div class="text-center"> 내비게이터 </div> |
▶ CategoryUserControl.ascx
1 2 3 4 5 6 7 8 |
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CategoryUserControl.ascx.cs" Inherits="TestProject.CategoryUserControl" %> <div class="text-center"> 카테고리 </div> |
▶ CatalogUserControl.ascx
1 2 3 4 5 6 7 8 |
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CatalogUserControl.ascx.cs" Inherits="TestProject.CatalogUserControl" %> <div class="text-center"> 카탈로그 </div> |
▶ CopyrightUserControl.ascx
1 2 3 4 5 6 7 8 |
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CopyrightUserControl.ascx.cs" Inherits="TestProject.CopyrightUserControl" %> <div class="text-center"> 저작권 </div> |
■ CustomValidator 클래스를 사용해 항목을 1개 이상 체크하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CustomValidator 클래스 : 항목을 1개 이상 체크하기</title> <script type="text/javascript"> function CheckValue(sender, e) { var checkBoxList = 'favoriteCheckBoxList'; var options = document.getElementById(checkBoxList).getElementsByTagName('input'); var ischecked = false; e.IsValid = false; for(i = 0; i < options.length; i++) { var option = options[i]; if(option.type == "checkbox") { if(option.checked) { ischecked = true; e.IsValid = true; } } } } </script> </head> <body> <form id="form" runat="server"> <div> <asp:CheckBoxList ID="favoriteCheckBoxList" runat="server" ValidationGroup="CheckGroup"> <asp:ListItem Value="0">ASP.NET</asp:ListItem> <asp:ListItem Value="1">Bootstrap</asp:ListItem> <asp:ListItem Value="2">C#</asp:ListItem> <asp:ListItem Value="3">Dapper</asp:ListItem> </asp:CheckBoxList> <asp:CustomValidator ID="favoriteCustomValidator" runat="server" ErrorMessage="반드시 하나 이상을 체크하세요." ClientValidationFunction="CheckValue" ValidationGroup="CheckGroup" Display="None" /> <asp:ValidationSummary runat="server" DisplayMode="List" ShowSummary="false" ShowMessageBox="true" ValidationGroup="CheckGroup" /> <asp:Button ID="submitButton" runat="server" ValidationGroup="CheckGroup" Text="제출" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ Bootstrap 누겟을 설치하는 방법을 보여준다. 1. Visual Studio를 실행한다. 2. [도구] / [NuGet 패키지 관리자] / [패키지 관리자 콘솔] 메뉴를 실행한다.
■ CustomValidator 클래스를 사용해 약관 동의하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CustomValidator 클래스 : 약관 동의하기</title> <script> function ValidationConfirmCheckBox(sender, e) { if(document.getElementById("<%= confirmCheckBox.ClientID %>").checked == true) { e.IsValid = true; } else { e.IsValid = false; } } </script> </head> <body> <form id="form" runat="server"> <div> <label for="optGender"> <asp:Literal ID="Literal1" runat="server">이용 약관</asp:Literal>: </label> <div> <p>회원 이용 약관에 동의하셔야 회원가입을 하실 수 있습니다.</p> <asp:TextBox ID="agreementTextBox" runat="server" Style="font-size:9pt;" Width="100%" Height="80px" TextMode="MultiLine"> </asp:TextBox> <div> <label> <asp:CheckBox ID="confirmCheckBox" runat="server" Checked="false" /> <asp:Literal ID="agreeLicenseLiteral" runat="server"> 위 약관에 동의합니다.(Accept the license) </asp:Literal> </label> </div> <asp:CustomValidator ID="confirmCustomValidator" runat="server" ErrorMessage="약관에 동의하셔야 합니다." ClientValidationFunction="ValidationConfirmCheckBox"> </asp:CustomValidator> <asp:ValidationSummary ID="validationSummary" runat="server" ShowSummary="false" ShowMessageBox="true" /> <div> <asp:Button ID="submitButton" runat="server" Text="가입하기" /> </div> </div> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ ValidationSummary 클래스를 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ValidationSummary 클래스 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <h3>유효성 검사 요약 컨트롤</h3> 아이디 : <asp:TextBox ID="userIDTextBox" runat="server" /> <asp:RequiredFieldValidator ID="userIDRequiredFieldValidator" runat="server" ControlToValidate="userIDTextBox" Display="None" ErrorMessage="아이디를 입력해주시 바랍니다."> </asp:RequiredFieldValidator> <br /> 암호 : <asp:TextBox ID="passwordTextBox" runat="server" TextMode="Password"> </asp:TextBox> <asp:RequiredFieldValidator ID="passwordRequiredFieldValidator" runat="server" ControlToValidate="passwordTextBox" Display="None" ErrorMessage="암호를 입력해주시기 바랍니다."> </asp:RequiredFieldValidator> <hr /> <asp:LinkButton ID="loginLinkButton" runat="server"> 로그인 </asp:LinkButton> <br /> <asp:ValidationSummary ID="validationSummary" runat="server" ShowMessageBox="true" ShowSummary="true" DisplayMode="BulletList" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ Localize 클래스를 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Localize 클래스 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:Localize ID="localize1" runat="server" Text="안녕하세요." /> <hr /> <asp:Localize ID="localize2" runat="server" Mode="Encode" Text="<hr /><em>안녕하세요.</em>" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { } #endregion } } |
TestProject.zip
■ Substitution 클래스를 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <%@ OutputCache Duration="60" VaryByParam="None" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Substitution 클래스 사용하기</title> </head> <body> <form id="form" runat="server"> <div> 캐싱 적용 : <asp:Label ID="label" runat="server" /> <hr /> 캐싱 미적용 : <asp:Substitution ID="substitution" runat="server" MethodName="GetCurrentTime" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
using System; using System.Web; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { this.label.Text = DateTime.Now.ToLongTimeString(); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 현재 시간 구하기 - GetCurrentTime(context) /// <summary> /// 현재 시간 구하기 /// </summary> /// <param name="context">컨텍스트</param> /// <returns>현재 시간</returns> private static string GetCurrentTime(HttpContext context) { return DateTime.Now.ToLongTimeString(); } #endregion } } |
TestProject.zip
■ Calendar 클래스의 SelectionChanged 이벤트를 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Calendar 클래스 : SelectionChanged 이벤트 사용하기</title> </head> <body> <form id="form" runat="server"> <div> 전달 값 : <asp:Label ID="messageLabel" runat="server" /> <asp:Calendar ID="calendar" runat="server" OnSelectionChanged="calendar_SelectionChanged" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(!String.IsNullOrEmpty(Request.QueryString["Date"])) { this.messageLabel.Text = Request.QueryString["Date"]; } else { this.messageLabel.Text = "(없음)"; } } #endregion #region 달력 선택 변경시 처리하기 - calendar_SelectionChanged(sender, e) /// <summary> /// 달력 선택 변경시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void calendar_SelectionChanged(object sender, EventArgs e) { DateTime selectedDate = this.calendar.SelectedDate; int year = selectedDate.Year; int month = selectedDate.Month; int day = selectedDate.Day; string url = string.Format ( "{3}?Date={0}-{1}-{2}", year, month, day, Request.ServerVariables["SCRIPT_NAME"] ); Response.Redirect(url); } #endregion } } |
TestProject.zip
■ ASP.NET 표준 컨트롤을 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ASP.NET 표준 컨트롤 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <table style="width: 500px"> <tr> <td style="width:60px">이용 약관</td> <td style="width:100px"> <asp:CheckBox ID="agreeCheckBox" runat="server" Width="122px" Checked="true" Text="동의합니다." /> </td> </tr> <tr> <td style="width:60px">취미</td> <td style="width:100px"> <asp:CheckBoxList ID="hobbyCheckBoxList" runat="server" Width="202px" RepeatLayout="Flow" RepeatDirection="Horizontal" RepeatColumns="2"> <asp:ListItem Selected="True" Value="S">축구</asp:ListItem> <asp:ListItem Value="V">배구</asp:ListItem> <asp:ListItem Selected="True" Value="B">농구</asp:ListItem> </asp:CheckBoxList> </td> </tr> <tr> <td style="width:60px">성별</td> <td style="width:100px"> <asp:RadioButton ID="manRadioButton" runat="server" GroupName="Gender" Checked="true" Text="남자" /> <asp:RadioButton ID="womanRadioButton" runat="server" GroupName="Gender" Text="여자" /> </td> </tr> <tr> <td style="width:60px">결혼 여부</td> <td style="width:100px"> <asp:RadioButtonList ID="weddingRadioButtonList" runat="server" Width="110px" RepeatLayout="Flow" RepeatDirection="horizontal"> <asp:ListItem Selected="True">미혼</asp:ListItem> <asp:ListItem>기혼</asp:ListItem> </asp:RadioButtonList> </td> </tr> <tr> <td style="width:60px;height:24px">직업</td> <td style="width:100px;height:24px"> <asp:DropDownList ID="jobDropDownList" runat="server"> <asp:ListItem>회사원</asp:ListItem> <asp:ListItem Selected="True">공무원</asp:ListItem> <asp:ListItem>백수</asp:ListItem> </asp:DropDownList> </td> </tr> <tr> <td style="width:60px">특기</td> <td style="width:100px"> <asp:ListBox ID="favoriteListBox" runat="server" SelectionMode="Multiple"> </asp:ListBox> </td> </tr> </table> <br /> <asp:Button ID="okButton" runat="server" Text="확인" OnClick="okButton_Click" /><br /> <br /> <asp:Label ID="displayLabel" runat="server" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
using System; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected //////////////////////////////////////////////////////////////////////////////// Event #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { SetFavoriteListBoxData(); } } #endregion #region 확인 버튼 클릭시 처리하기 - okButton_Click(sender, e) /// <summary> /// 확인 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void okButton_Click(object sender, EventArgs e) { StringBuilder stringBuilder = new StringBuilder(); if(this.agreeCheckBox.Checked) { stringBuilder.Append("[1] " + this.agreeCheckBox.Text + "<br />"); } if(this.hobbyCheckBoxList.Items[0].Selected) { stringBuilder.Append("[2] " + this.hobbyCheckBoxList.Items[0].Value + "<br />"); } if(this.hobbyCheckBoxList.Items[1].Selected) { stringBuilder.AppendFormat("[2] {0}<br/>", this.hobbyCheckBoxList.Items[1].Value); } if(this.hobbyCheckBoxList.Items[2].Selected) { stringBuilder.AppendFormat("[2] {0}<br/>", this.hobbyCheckBoxList.Items[2].Value); } if(this.manRadioButton.Checked) { stringBuilder.AppendFormat("[3] {0} 선택<br />", this.manRadioButton.Text); } else { stringBuilder.AppendFormat("[3] {0} 선택<br />", this.womanRadioButton.Text); } stringBuilder.AppendFormat("[4] {0}<br />", this.weddingRadioButtonList.SelectedItem.Text); stringBuilder.AppendFormat("[5] {0}<br />", this.jobDropDownList.Items[this.jobDropDownList.SelectedIndex].Value); for(int i = 0; i < this.favoriteListBox.Items.Count; i++) { if(this.favoriteListBox.Items[i].Selected) { stringBuilder.AppendFormat("[6] {0}<br />", this.favoriteListBox.Items[i].Value); } } foreach(ListItem listItem in this.favoriteListBox.Items) { if (listItem.Selected) { stringBuilder.AppendFormat("[6] {0}<br />", listItem.Text); } } this.displayLabel.Text = stringBuilder.ToString(); } #endregion //////////////////////////////////////////////////////////////////////////////// Function #region 특기 리스트 박스 데이터 설정하기 - SetFavoriteListBoxData() /// <summary> /// 특기 리스트 박스 데이터 설정하기 /// </summary> private void SetFavoriteListBoxData() { this.favoriteListBox.Items.Add("C#"); this.favoriteListBox.Items.Add("ASP.NET"); ListItem listItem = new ListItem(); listItem.Text = "자바스크립트"; listItem.Value = "JavaScript"; this.favoriteListBox.Items.Add(listItem); listItem = new ListItem("닷넷", ".NET"); this.favoriteListBox.Items.Add(listItem); } #endregion } } |
TestProject.zip
■ DropDownList 클래스를 사용해 동적으로 생성하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>DropDownList 클래스 : 동적으로 생성하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:PlaceHolder ID="placeHolder" runat="server" /> <hr /> <asp:Button ID="getValueButton" runat="server" Text="값 구하기" OnClick="getValueButton_Click" /> <hr /> <asp:Label ID="messageLabel" runat="server" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
using System; using System.Web.UI; using System.Web.UI.WebControls; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { for(int i = 1; i <= 2; i++) { DropDownList dropDownList = new DropDownList(); dropDownList.ID = string.Format("dropDownList{0}", i); dropDownList.Items.Add(new ListItem("Text1", "Value1")); dropDownList.Items.Add(new ListItem("Text2", "Value2")); dropDownList.Items.Add(new ListItem("Text3", "Value3")); this.placeHolder.Controls.Add(dropDownList); } } #endregion #region 값 구하기 버튼 클릭시 처리하기 - getValueButton_Click(sender, e) /// <summary> /// 값 구하기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void getValueButton_Click(object sender, EventArgs e) { this.messageLabel.Text = "선택된 값 : "; for(int i = 1; i <= 2; i++) { DropDownList dropDownList = this.placeHolder.FindControl(String.Format("dropDownList{0}", i)) as DropDownList; if(dropDownList != null) { this.messageLabel.Text += dropDownList.SelectedValue + ", "; } } } #endregion } } |
TestProject.zip
■ ImageButton 클래스의 Click 이벤트를 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ImageButton 클래스 : Click 이벤트 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:ImageButton ID="listImageButton" runat="server" AlternateText="리스트" ToolTip="리스트" OnClick="listImageButton_Click" /> <asp:Label ID="messageLabel" runat="server" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { this.listImageButton.ImageUrl = "~/Images/list.png"; } #endregion #region 리스트 버튼 클릭시 처리하기 - listImageButton_Click(sender, e) /// <summary> /// 리스트 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void listImageButton_Click(object sender, ImageClickEventArgs e) { this.messageLabel.Text = $"이미지 버튼 클릭 좌표 : X = {e.X}, Y = {e.Y}"; } #endregion } } |
TestProject.zip
■ ImageButton 클래스의 ImageUrl 속성을 사용하는 방법을 보여준다. ▶ MainPage.aspx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs" Inherits="TestProject.MainPage" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>ImageButton 클래스 : ImageUrl 속성 사용하기</title> </head> <body> <form id="form" runat="server"> <div> <asp:ImageButton ID="writeImageButton" runat="server" AlternateText="글쓰기" ToolTip="글쓰기" OnClick="writeImageButton_Click" /> <asp:ImageButton ID="listImageButton" runat="server" AlternateText="리스트" ToolTip="리스트" OnClick="listImageButton_Click" /> </div> </form> </body> </html> |
▶ MainPage.aspx.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System; using System.Web.UI; namespace TestProject { /// <summary> /// 메인 페이지 /// </summary> public partial class MainPage : Page { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 페이지 로드시 처리하기 - Page_Load(sender, e) /// <summary> /// 페이지 로드시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void Page_Load(object sender, EventArgs e) { this.writeImageButton.ImageUrl = "~/Images/write.png"; this.listImageButton.ImageUrl = "~/Images/list.png"; } #endregion #region 글쓰기 버튼 클릭시 처리하기 - writeImageButton_Click(sender, e) /// <summary> /// 글쓰기 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void writeImageButton_Click(object sender, ImageClickEventArgs e) { Response.Write("글쓰기 버튼 클릭됨.<br />"); } #endregion #region 리스트 버튼 클릭시 처리하기 - listImageButton_Click(sender, e) /// <summary> /// 리스트 버튼 클릭시 처리하기 /// </summary> /// <param name="sender">이벤트 발생자</param> /// <param name="e">이벤트 인자</param> protected void listImageButton_Click(object sender, ImageClickEventArgs e) { Response.Write("리스트 버튼 클릭됨.<br />"); } #endregion } } |
TestProject.zip