MVC에서는 Routing 과 Controller Method를 통해 View page를 호출을 한다
using System.Web.Mvc;
namespace MvcMyApplication2.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Detail()
{
return RedirectToAction("Index");
}
}
}
|
HomeController 에는 3개의 Index(), About(), Detail() action Method가 있다.
각 action은 다음과 같이 주소표시줄에 표기된다.
Index()
|
/Home/Index
|
About()
|
/Home/About
|
Detail()
|
/Home/Detail
|
Index() action은 view를 리턴한다. 어떤 action은 다른 type의 action 결과를 리턴할 수 있다.
예를 들어 Detail() action처럼 Index() action을 요청하는 RedirectToActionResult를 리턴할 수 있다.
Index() action의 View();는
반드시 웹서버에 \Views\Home\Index.aspx가 있어야 한다.
만약 View(“Fred”); 를 리턴하면
\Views\Home\Fred.aspx 실행된다.
View에 내용추가
View는 다양한 script내용을 포함할 수 있는 html문서이다.
예를 들어 날짜를 출력하는 view를 보겠다.
Add.aspx
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Add</title>
</head>
<body>
<div>
The current date and time is<br />
<% Response.Write(DateTime.Now); %>
</div>
</body>
</html>
|
이 구분기호 <% 과 %> C#에서 쓰여진 script이다.
Response.Write() Method는 브라우저 내용에 현재 날짜를 보여준다.
이 구분기호 <% 과 %>은 하나 또는 더 많은 세크먼트를 실행하는데 사용된다.
Result
The current date and time is
2009-04-18 오후 10:45:43
|
Add2.aspx
<%@ Page Title=”” Language=”C#” Inherits=”System.Web.Mvc.ViewPage” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<title>Add</title>
</head>
<body>
<div>
The current date and time is<br />
<%=DateTime.Now %>
</div>
</body>
</html>
|
<%=%> 구분기호는 Response.Write() 를 간략하게 쓰는 기호이다.
|
Result
The current date and time is
2009-04-18 오후 10:45:43
|
View에서 HTML Helper 사용하기
HTML Helper는 Textbox, Link, Dropdown List, List Box등의 표준 HTML 요소를 사용할 수 있게 한다.
Login.aspx
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Login Form</title>
</head>
<body>
<div>
<% using (Html.BeginForm())
{ %>
<label for="UserName">User Name:</label>
<br />
<%= Html.TextBox("UserName") %>
<br /><br />
<label for="Password">Password:</label>
<br />
<%= Html.Password("Password") %>
<br /><br />
<input type="submit" value="Log in" />
<% } %>
</div>
</body>
</html>
|
HTML Source
<form action="/Home/Login" method="post">
<label for="UserName">User Name:</label>
<br />
<input id="UserName" name="UserName" type="text" value="" />
<br /><br />
<label for="Password">Password:</label>
<br />
<input id="Password" name="Password" type="password" />
<br /><br />
<input type="submit" value="Log in" />
</form>
|
위에서 보듯이 HTML Helper는 각 HTML 요소로 변경된다. 기존의 서버컨트롤과는 다른 string만 변경하여 리턴을 해준다. ( 랜더링 작업이 없다. )
View에 View Data 사용하기
Controller 에서 ViewData["Message"] = "Welcome to ASP.NET MVC!"; 설정하면
ViewData["Message"]를 View Page에서 사용할 수 있다.
<%= Html.Encode(ViewData["Message"]) %> 하면 View Page에 Welcome to ASP.NET MVC! 라고 출력이 된다.
Custom HTML Helper 만들기
ASP.NET MVC의 HTML Helper의 종류는 다음과 같다.
- Html.ActionLink()
- Html.BeginForm()
- Html.CheckBox()
- Html.DropDownList()
- Html.EndForm()
- Html.Hidden()
- Html.ListBox()
- Html.Password()
- Html.RadioButton()
- Html.TextArea()
- Html.TextBox()
<label>관련된 static Method를 만들려고 한다.
우리가 가끔 string 관련 함수를 만들어 return 하는 방식과 같다.
Helpers/LabelHelper.cs
using System;
namespace MvcMyApplication2.Helpers
{
public class LabelHelper
{
public static string Label(string target, string text)
{
return String.Format("<label for='{0}'>{1}</label>", target, text);
}
}
}
|
HTML 요소의 특성에 맞게 파라메터를 받고 스트링 문자열을 만들어 return 한다.
이렇게 만든 클래스를 사용해보자
<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import! Namespace="MvcMyApplication2.Helpers " %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Index2</title>
</head>
<body>
<div>
<% using (Html.BeginForm())
{ %>
<%= LabelHelper.Label("firstName", "First Name:") %>
<br />
<%= Html.TextBox("firstName")%>
<br /><br />
<%= LabelHelper.Label("lastName", "Last Name:") %>
<br />
<%= Html.TextBox("lastName")%>
<br /><br />
<input type="submit" value="Register" />
<% } %>
</div>
</body>
</html>
|
Result

HTML Helpers Extension Method 만들기
HtmlHelper 클래스에 Label() 확장 메소드를 추가하기
1. 클래스는 Static class
2. Static class에 Extension Method를 정의 해야한다.
Helpers/LabelExtensions.cs
using System;
using System.Web.Mvc;
namespace MvcMyApplication2.Helpers
{
public static class LabelExtensions
{
public static string Label(this HtmlHelper helper, string target, string text)
{
return String.Format("<label for='{0}'>{1}</label>", target, text);
}
}
}
|
작성 후 View Page에 Import! 하면 아래 그림과 같이 출력이 된다.

