理解ASP.NET MVC中的HTML Helpers

 1 @helper listItems(string[] items)
 2 {
 3     <ol>
 4         @foreach (var item in items)
 5         {
 6             <li>@item</li>
 7         }
 8     </ol>
 9 }
10 <h1>页面内自定义helper</h1>
11 @listItems(new string[] { "项目一","项目二","项目三"})

02 内置Html Helpers

HTML ElementStandard Html Helpers ExampleStrongly Typed HTML Helpers Example
TextBox@Html.TextBox("Textbox1", "val")

Output: <input />

@Html.TextBoxFor(m=>m.Name)

Output: <input />

TextArea@Html.TextArea("Textarea1", "val", 5, 15, null)

Output: <textarea cols="15" >val</textarea>

@Html.TextArea(m=>m.Address , 5, 15, new{}))

Output: <textarea cols="15" >Addressvalue</textarea>

Password@Html.Password("Password1", "val")

Output: <input />

@Html.PasswordFor(m=>m.Password)

Output: <input />

Hidden Field@Html.Hidden("Hidden1", "val")

Output: <input />

@Html.HiddenFor(m=>m.UserId)

Output: <input />

CheckBox@Html.CheckBox("Checkbox1", false)

Output: <input /> <input name="myCheckbox" type="hidden" value="false" />

@Html.CheckBoxFor(m=>m.IsApproved)

Output: <input /> <input name="myCheckbox" type="hidden" value="false" />

RadioButton@Html.RadioButton("Radiobutton1", "val", true)

Output: <input checked="checked" type="radio" value="val" />

@Html.RadioButtonFor(m=>m.IsApproved, "val")

Output: <input checked="checked" type="radio" value="val" />

Drop-down list@Html.DropDownList (“DropDownList1”, new SelectList(new [] {"Male", "Female"}))

Output: <select > <option>M</option> <option>F</option> </select>

@Html.DropDownListFor(m => m.Gender, new SelectList(new [] {"Male", "Female"}))

Output: <select > <option>Male</option> <option>Female</option> </select>

Multiple-selectHtml.ListBox(“ListBox1”, new MultiSelectList(new [] {"Cricket", "Chess"}))

Output: <select > <option>Cricket</option> <option>Chess</option> </select>

Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new [] {"Cricket", "Chess"}))

Output: <select > <option>Cricket</option> <option>Chess</option> </select>