ASP.NET MVC5 - HTML Helpers

HTML Helpers 可以用來 create HTML components, 可以用來協助 display strongly typed Model
  • Label Helpers : 產生 HTML 的 <label></label>
@Html.Label("Email Address")
為了要讓這一個 lable 有 css, 我們可以 create 一個 class 的 property, 但是 class 在 c# 是 reserved word, 所以要在 class 前面加一個 @ 表示 escaped char
@Html.Label("Email Address", new { @class = "control-label"})
但是 Label 裡面有一個 HTML attribute 叫做 for, 這一個 for 是要跟 input 綁住關係的, 如果要加上這一個 for 在 Label, 就必須要用 HTML.LabelFor(), 裡面參數可以用 lambda function 選擇我們要的 Model
@Html.LabelFor(m => m.Username, "Email address", new { @class = "control-label" })
上面的 code 和下面的 code 是完全一樣的
<label for="username" class="sr-only">Email address</label>

  • Html.TextBoxFor() : 產生 Html 的 <input>
 @Html.TextBoxFor(m => m.Username, new { @class = "form-control", placeholder = "Email address", autofocus = "" })
上面的 code 跟下面的 code 是完全一樣的
<input id="username" name="username" class="form-control" placeholder="Email address"
               autofocus="" value='@(Model?.Username ?? "")'>

  • Url.Action() : create a link to an action method using the controller and action name
Url.Action("Index", "Home")

  • Url.ActionLink() : generate the url and the entire link or anchor tag with the url that is set to that action method, Our Products 表示 link 的 context, 等同於 <a>Our Products</a>
@Html.ActionLink("Our Products", "Index", "Product")

  • Html.BeginForm :
Index = Action name
Login = Controller name
new { ReturnUrl = Request.QueryString[“ReturnUrl”] }, authentication 的東西, 當你想要 access a page 但是沒有 login 的時候, 這時 ASP.NET 就會 redirect to the login page
FormMethod.Post = 用 http POST method send a request
new { @class = “form-signin” } = css 的 class
    @using (Html.BeginForm("Index", "Login",
        new { ReturnUrl = Request.QueryString["ReturnUrl"] },
        FormMethod.Post,
        new { @class = "form-signin" }))
{

}

Inline Html Helpers
如果不想一直寫一樣的 html code, 這時候可以使用 inline html helpers, 我們常常在 mobile version 可以看到三條線的 hamberger bars, <span class="icon-bar"></span> 一條線代表一個 span tag with a class icon-bar, 但是我們要 5 條就要複製 5 次, 這個時候就可以用 Inline Html Helpers
<!DOCTYPE html> 的最上方定義 server side code, 之後再回到原本放上 的地方, 把 <span class="icon-bar"></span> 換成 @IconBars(2) 就可以了
@helper IconBars(int count)
{
    for (int i = 0; i < count; i++)
    {
        <span class="icon-bar"></span>
    }
}

  • Custom Html Helpers
可以自己 create 一個 Html Helpers, 顯示 Copyright

留言

這個網誌中的熱門文章

ASP.NET Web API - DTOs

Scaffold Identity into the Current Project

Passing data from controller to the view