MVC 中的@Html控件

MVC @Html控件

   傳統的Html元素不能和服務端數據進行綁定 HtmlHelper類提供了一系列的方法來生成Html元素 並可以實現與數據綁定在一起 然後生成Html

Html.BeginForm(actionName , controllerName , FormMethod , htmlAttribute)

創建一個表單

actionName 和 controllerName

這兩個參數表示表單要提交到哪個controllerName下的哪個Action方法中

FormMethod

此參數是一個枚舉 表示表單提交方式  GET or POST

htmlAttribute

表示form元素的Html屬性 是一個object對象 使用new {html屬性名字="值"} class也是html屬性 但同時它是C#關鍵字 只能這樣指定:new {@class="formstyle"}

 

Html.EndForm()

表示表單結束 如

1 @Html.BeginForm("index", "default", FormMethod.Post, new {id="form1"})
2 <input type="text" />
3 @{Html.EndForm();}

BeginForm方法返回System.Web.Mvc.Html.MvcForm類型 如果不用中括號括起來 則表示要輸出該方法返回的值 EndForm無返回值 所以也需要使用中括號括起來 最後一個參數通過objecr來指定它的Html屬性

Html.Raw()

@Html.Raw() 方法輸出帶有html標籤的字符串,如:
@Html.Raw("<div style='color:red'>輸出字符串</div>")
結果:輸出字符串

Html.RadioButton(name,value,Ischecked,htmlAttribute)

創建單選按鈕

name

單選按鈕的name

value

單選按鈕的值

Ischecked

是否是選中狀態

1 @{Html.BeginForm("index", "default", FormMethod.Post);}
2     男人 @Html.RadioButton("radiobtn","man",true,new{@class="radioStyle"})
3     女人 @Html.RadioButton("radiobtn","woman",false,new{@class="radioStyle"})
4 @{Html.EndForm();}

 

Html.RadioButtonFor(expression,value,htmlAttribute)

同樣是創建單選按鈕的方法 但+For後綴的方法可以使用強類型作爲參數expression的參數 推導出類型的屬性 它可以將類型的屬性名字作爲表單元素的name的值

expression

類型爲System.Linq.Express.Expression.<Fun<dynamic,Tproperty>>的表達式  如

1 @model Course.Models.Employee
2 @{Html.BeginForm("index", "default", FormMethod.Post);}
3     北京 @Html.RadioButtonFor(n=>n.Address,"北京",new{@class="radioStyle",@checked="checked"})
4     上海 @Html.RadioButtonFor(n=>n.Address,"上海",new{@class="radioStyle"})
5 @{Html.EndForm();}

 

Html.CheckBox()

創建複選框

不建議使用此方法來創建複選框 服務端不好獲取值 請直接使用input 注意每個複選框需要有value值 否則獲取的選中的複選框的值永遠是on

1 <input type="checkbox" class="Book" value="1" name="Books" checked="checked"/>民謠<br/>
2 <input type="checkbox" class="Book" value="2" name="Books" checked="checked"/>電子<br/>
3 <input type="checkbox" class="Book" value="3" name="Books" />低保真<br/>

在Action中這樣獲取

1 public ActionResult Editor(int[] Books)
2 {
3     foreach (var item in Books)
4     {
5     }
6 }

 

Html.CheckBoxFor()

不建議使用此方法

 

Html.DropDownList(name , selectList , defaultSelected,htmlAttribute)

創建下拉選項

name

下拉選項的name

selectList

一個IEnumerable<SelectListItem>集合 集合中的每個選項是SelectListItem類型的 我們可以在Action中創建實現了IEnumerable<selectListItem>接口的集合 然後將集合作爲此方法的第二個參數 如

複製代碼
複製代碼
 1 public ActionResult Index()
 2 {
 3     List<SelectListItem> itemList = new List<SelectListItem>
 4     {
 5         new SelectListItem{Text="荔枝",Value="荔枝", Selected=false},
 6         new SelectListItem{Text="番茄",Value="番茄",Selected=false},
 7         new SelectListItem{Text="芒果",Value="芒果",Selected=false}
 8     };
 9     ViewData["choose"] = itemList;
10     return View();
11 }
複製代碼
複製代碼

在視圖中

1 @{Html.BeginForm("index", "default", FormMethod.Post);}
2     @Html.DropDownList("choose",ViewData["choose"] as IEnumerable<SelectListItem>,new{@class="selectStyle"})
3 @{Html.EndForm();}

defaultSelected

一個文本 表示默認選擇的項 可選

1 @Html.DropDownList("choose",ViewData["choose"] as IEnumerable<SelectListItem>,"請選擇",new{@class="selectStyle"})

使用Linq創建下拉選項集合 如

複製代碼
複製代碼
 1 public ActionResult Index()
 2 {
 3     List<Employee> empList = new List<Employee>
 4     {
 5             new Employee{ ID=1, Name="sam"},
 6             new Employee{ ID=2, Name="leo"},
 7             new Employee{ ID=3, Name="korn"}
 8     };
 9     List<SelectListItem> itemList = (from n in empList.ToList()
10                                         select new SelectListItem { Text = n.Name, Value = n.ID.ToString(), Selected = false }).ToList();
11 
12     ViewData["choose"] = itemList;
13     return View();
14 }
複製代碼
複製代碼

還可以直接創建SelectList對象來得到同樣的結果 這種方式更簡潔 如

複製代碼
複製代碼
 1 public ActionResult Index()
 2 {
 3     List<Employee> empList = new List<Employee>
 4     {
 5             new Employee{ ID=1, Name="sam"},
 6             new Employee{ ID=2, Name="leo"},
 7             new Employee{ ID=3, Name="korn"}
 8     };
 9     SelectList selecyList = new SelectList(empList, "ID", "Name");
10     ViewData["choose"] = selecyList;
11     return View();
12 }
複製代碼
複製代碼

在視圖中只需兩個參數 參數1爲choose 引用的是ViewData["choose"]中的鍵

1 @Html.DropDownList("choose","請選擇")

 

Html.DropDownListFor(expression,selectList,htmlAttribute)

同樣是創建下拉選項的方法 但+For後綴的方法可以使用強類型作爲參數expression的參數 推導出類型的屬性 它可以將類型的屬性名字作爲下拉選項元素的name的值

expression

類型爲System.Linq.Express.Expression.<Fun<dynamic,Tproperty>>的表達式

selectList

類型爲SelectLlist的對象

複製代碼
複製代碼
 1 public ActionResult Index()
 2 {
 3     List<Employee> empList = new List<Employee>
 4     {
 5             new Employee{ ID=1, Name="sam"},
 6             new Employee{ ID=2, Name="leo"},
 7             new Employee{ ID=3, Name="korn"}
 8     };
 9     SelectList selectList = new SelectList(empList, "ID", "Name");
10     ViewData["choose"] = selectList;
11     return View();
12 }
複製代碼
複製代碼

在視圖中

1 @model Course.Models.Employee
2 @{Html.BeginForm("index", "default", FormMethod.Post);}
3     @Html.DropDownListFor(n=>n.Name,ViewData["choose"] as SelectList,new{@class="selectStyle"})
4 @{Html.EndForm();}

 

Html.ActionLink(linkText , actionName , controlName , routeValues , htmlAttribut)

   //var url = "Url.Action("SearchResult")" + "?name=" + keyword;

創建超鏈接

linkText

超鏈接文本

actionName

提交到哪個Action處理

controlName

提交到哪個控制器 可選 默認就是當前視圖所屬的Action所在的控制器

routeValues

object對象 設置超鏈接查詢字符 跟設置html屬性是一樣的 如new {id=1,name="sam"}

1 @Html.ActionLink("詳細","Detail",new { id=1})

生成的超鏈接爲

1 生成對應的超鏈接爲:
2 <a href="default/Detail/1">詳細</a>

提供多個查詢字符

1 Html.ActionLink("詳細","Detail",new { id=1,name="sam"})
2 生成對應的超鏈接爲:
3 <a href="default/Detail?id=1&name=1">詳細</a>

 

Html.Partial()

將分佈視圖渲染到當前視圖頁面 該方法具有多個重載版 所有參數介紹如下

partialName

參數爲分佈視圖名稱

viewData

一個ViewDataDictionary類型的對象

model

分佈視圖需要使用的強類型對象

分佈視圖可以手動在當前視圖的目錄中創建 擴展名還是cshtml 只不過裏面沒有<html>/<head>/<body>標籤 你可以在分佈視圖中編寫body以下級別的html元素 也可以寫Js和服務端腳本 除了沒有幾個主體標籤 其它和視圖都是一樣的 可以右擊Action - 添加視圖 選擇分佈視圖 如

20130906185121

打開TestPartial文件 輸入以下代碼做個測試

<div style="background:#010067;width:200px;height:100px;padding-top:50px;text-align:center;color:white;">
    <label style="color:red;font-size:20px;font-weight: bolder;vertical-align:middle;">+</label>
    <label style="vertical-align:middle;">這個框裏的內容是分佈視圖TestPartial</label>
</div>

接着打開Index視圖 調用此方法來加載分佈視圖TestPartial

<body>
    <div style="background:#ffd800;width:200px;padding:10px;">
        這是Index視圖<br /><br />
        @Html.Partial("TestPartial")
    </div>
</body>

運行http://localhost:8559/default/index 結果如圖:

1

viewData參數和model參數的用法如下

複製代碼
複製代碼
<body>
    <div style="background:#ffd800;width:200px;padding:10px;">
        這是Index視圖<br /><br />
        @Html.Partial("TestPartial", new Course.Models.Employee{ ID=1, Name="sam"}, new ViewDataDictionary { {"music1","Free Jazz"},{"music2","BossaNova"}})
    </div>
</body>
複製代碼
複製代碼

在分佈視圖中可獲取viewData和model model必須聲明一下

複製代碼
複製代碼
@model Course.Models.Employee
<div style="background:#010067;width:200px;height:100px;padding-top:50px;text-align:center;color:white;">
    <label style="color:red;font-size:20px;font-weight: bolder;vertical-align:middle;">+</label>
    <label style="vertical-align:middle;">@Model.Name</label>
    <p><label style="vertical-align:middle;">@ViewData["music1"]</label></p>
    <p><label style="vertical-align:middle;">@ViewData["music2"]</label></p>
</div>
複製代碼
複製代碼

運行http://localhost:8559/default/index 結果如圖:

2

 

Html.RenderPartial()

與Partial方法有類似的行爲 區別在於Partial是將分佈視圖作爲字符串加入主視圖 而RenderPartial則是將分佈式圖寫入響應輸出流 在性能上RenderPartial要優於前者 但以往內此方法不返回值 所以必須使用中括號括起來

@{Html.RenderPartial("TestPartial");}
@{Html.RenderPartial("TestPartial", new Course.Models.Employee{ ID=1, Name="sam"}, new ViewDataDictionary { {"music1","Free Jazz"},{"music2","BossaNova"}});}

 

Html.Action()

調用一個子操作(Action) 並以Html形式返回結果

actionName

Action的名稱

controllerName

控制器的名稱

routeValues

路由參數 格式:new {id=xx,code=xxx}

此方法與Partial類似 區別在於 Partial方法不經過Action處理 它直接加載一個分部視圖頁面 而Action方法會先經過Action處理再加載分佈視圖 其用法如下

public ActionResult Menu()
{
    return PartialView("Menu");
}

右擊Menu方法 創建一個分部視圖Menu 打開分部視圖 輸入如下代碼

複製代碼
複製代碼
<div style="background: #010067; text-align: center; color: white;">
    <p>這是分佈視圖</p>
    <ul>
        <li>坂本龍一  </li>
        <li>Ian Brown</li>
        <li>Ataraxia </li>
    </ul>
</div>
複製代碼
複製代碼

在Index頁面調用此方法

<body>
    <div style="background:#ffd800;width:200px;padding:10px;">
        這是Index視圖<br /><br />
        @Html.Action("Menu")
    </div>
</body>

結果

tt

 

Html.RenderAction()

與Action方法有類似的行爲 區別在於Action方法是將分佈視圖作爲字符串加入主視圖 而RenderAction則是將分佈式圖寫入響應輸出流 在性能上RenderAction要優於前者 但以往內此方法不返回值 所以必須使用中括號括起來

 

類似的Html輔助方法還有Html.Hidden()、Html.PassWord()、Html.TextBox() 略 ……

 

UrlHelper類提供了方法用於生成URL

Content()

將一個虛擬的、相對的URL轉換爲應用程序的絕對URL 如

1 <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

Encode()

對URL地址進行加密

1 @Url.Encode("http://www.cnblogs.com/")

生成http%3a%2f%2fwww.cnblogs.com%2f

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章