MVC-HtmlHelper簡單總結


Asp.Net MVC - Htmlhelper 總結

HtmlHelper是一個返回Html字符串的方法。返回的字符串可以是任意類型。例如你可以使用HtmlHelper方法返回一個標准的html標簽<input> <button> <img>等等。

你也可以自定義HtmlHelper方法,返回一些復雜的html,來展示數據。

Razor編碼

首先需要認識了解一下Razor的編碼

在Razor中返回類型為IHtmlString的都會被編碼成html,其他都是string字符串。

//Controller
 string msgStr = "this is an html element: <input>";
 ViewBag.Msg = msgStr;
 ViewBag.Msg1 = new MvcHtmlString(msgStr);

Razor:

  • Html.Encode()返回類型為string。
  • Html.Raw()返回類型為IHtmlString。
  • MvcHtmlString.Create返回類型為繼承自IHtmlString的MvcHtmlStrin。
  • ViewBag是動態類型,Controller里ViewBag是什么類型,在Razor對應就是何種類型。

簡單總結下HtmlHelper的幾種擴展方法。

1. 視圖中的Helper方法

在razor頁面中使用@helper創建一個自定義的方法,該方法只能用在當前razor頁面中。

@helper ListingItems(string[] items)
    {
    <ol>
    @foreach (string item in items)
    {
    <li>@item</li>
    }
    </ol>
    }
    
    <h3>Programming Languages:</h3>
    
    @ListingItems(new string[] { "C", "C++", "C#" })
    
    <h3>Book List:</h3>
    
    @ListingItems(new string[] { "How to C", "how to C++", "how to C#" })

2. 常見的HtmlHelper擴展方法

該類型的Helper可以生成多種Hmtl控件如:text boxe checkbox等待。

首先聲明一個Model

[DisplayName("學生")]
public class Student
{
    public int StudentId { get; set; }
    [Display(Name="姓名")]
    public string StudentName { get; set; }
    public int Age { get; set; }
    public bool isNewlyEnrolled { get; set; }
    public string Password { get; set; }
    [DisplayFormat(DataFormatString = "{0:yyyy年MM月dd日}")]
    [Display(Name ="生日")]
    public DateTime BirthDay{get;set;}
}

1.1 TextBox

Razor:

@model Student
//傳遞一個null值
@Html.TextBox("StudentName", null, new { @class = "form-control" })  
//使用一個字符串,作為值
@Html.TextBox("StudentName", "this is value", new { @class = "form-control" } 
//Controller:ViewBag.StudentName="Janes";
//使用ViewBag獲取數據
@Html.TextBox("StudentName", (string)ViewBag.StudentName, new { @class = "form-control" })  
//Controller: StudentName="Janes";
//使用Model獲取數據
@Html.TextBox("StudentName", Model.StudentName, new { @class = "form-control" })  

Html:

<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="" />
<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="this is value" />
<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="Janes" />
<input class="form-control" id="StudentName"  name="StudentName"  type="text"  value="Janes" />

1.2 TextBoxFor

Razor:

@model Student
//Controller: StudentName="Janes";
@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })  

Html:

<input class="form-control" id="StudentName"  name="StudentName"  type="text" value="Janes" />

TextBox和TextBoxFor的區別:

  • @Html.TextBox是一個弱類型,@Html.TextBoxFor()是個強類型。

  • @Html.TextBox參數是一個字符串,@Html.TextBoxFor參數是一個lambda表達式。

  • @Html.TextBox如果屬性拼寫錯誤在編譯的時候不會報錯,只能在運行才會報錯。

  • @Html.TextBoxFor在編譯的時候會提示錯誤。


2.1 TextArea

TextArea()方法是一種若類型的方法,name參數是一個字符串。name參數可以是Model的屬性名。它將指定的屬性與textarea綁定在一起。因此,它會自動顯示文本區域中的Model的屬性值,反之亦然。

Razor:

@Html.TextArea("Textarea1", "val", 5, 15, new { @class = "form-control" })

Html:

<textarea class="form-control" cols="15" id="Textarea1" name="Textarea1" rows="5">val</textarea>

2.2 TextAreaFor

TextAreaFor方法是一種強類型的擴展方法。它為使用lambda表達式指定的Model中的屬性生成了一個多行的元素。TextAreaFor方法將指定的Model屬性綁定到textarea元素。因此,它會自動顯示文本區域中的Model屬性值,反之亦然。

Razor:

@model Student

@Html.TextAreaFor(m => m.Description, new { @class = "form-control" })  

Html:

<textarea class="form-control" cols="20"  id="Description"  name="Description"  rows="2"></textarea>

3.1 Password

Razor:

@Html.Password("OnlinePassword")

Html:

<input id="OnlinePassword"  name="OnlinePassword"  type="password"  value="" />

3.2 PasswordFor

Razor:

@model Student
//Controller: Password="mypassword";
@Html.PasswordFor(m => m.Password)

Html:

<input id="Password" name="Password" type="password" value="mypassword" />

4.1 Hidden

生成一個包含指定名稱、值和html屬性的輸入隱藏字段元素。
Razor:

@model Student
//Controller:StudentId=1;
@Html.Hidden("StudentId")

Html:

<input id="StudentId" name="StudentId" type="hidden" value="1" />

4.2 HiddenFor

是一種強類型擴展方法。它為使用lambda表達式指定的Model屬性生成一個隱藏的輸入元素。Hiddenfor方法將一個指定的Model屬性綁定到一個指定的對象屬性。因此,它自動將Model屬性的值設置為隱藏字段,反之亦然。

Razor:

@model Student
@Html.HiddenFor(m => m.StudentId)

Html:

<input data-val="true" id="StudentId" name="StudentId" type="hidden" value="1" />

5.1 CheckBox

Razor:

@Html.CheckBox("isNewlyEnrolled", true)

Html:

<input checked="checked" id="isNewlyEnrolled"  name="isNewlyEnrolled" type="checkbox" value="true" />

5.2 CheckBoxFor

Razor:

@model Student

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

Html:

<input data-val="true"  data-val-required="The isNewlyEnrolled field is required."  id="isNewlyEnrolled"  name="isNewlyEnrolled"   type="checkbox"    value="true" />
<input name="isNewlyEnrolled" type="hidden" value="false" />

6.1 RadioButton

Razor:

Male:   @Html.RadioButton("Gender","Male")  
Female: @Html.RadioButton("Gender","Female")  

Html:

Male: <input checked="checked"  id="Gender"    name="Gender"    type="radio"     value="Male" />

Female: <input id="Gender"    name="Gender"     type="radio"     value="Female" />

6.2 RadioButtonFor

Razor:

@model Student

@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")

Html:

<input checked="checked" id="Gender" name="Gender" type="radio" value="Male" />

<input id="Gender" name="Gender" type="radio" value="Female" />

7.1 DropDownList

Razor:

@model Student

@Html.DropDownList("StudentGender",   new SelectList(Enum.GetValues(typeof(Gender))),      "Select Gender",    new { @class = "form-control" })

Html:


<select class="form-control" id="StudentGender" name="StudentGender">
    <option>Select Gender</option> 
    <option>Male</option> 
    <option>Female</option> 
</select>

7.2 DropDownListFor

Razor:

@Html.DropDownListFor(m => m.StudentGender,     new SelectList(Enum.GetValues(typeof(Gender))),    "Select Gender")

Html:

<select class="form-control" id="StudentGender" name="StudentGender">
    <option>Select Gender</option> 
    <option>Male</option> 
    <option>Female</option> 
</select>

8.1 ListBox

Razor:

@Html.ListBox(“ListBox1”, new MultiSelectList(new [] {"Cricket", "Chess"}))

html:

<select id="ListBox1" multiple="multiple" name="ListBox1"> <option>Cricket</option> <option>Chess</option> </select>

9.1 Display

Razor:

@model Student

@Html.Display("StudentName")

Html:

Steve

9.2 DisplayFor

Raozr:

@model Student

@Html.DisplayFor(m => m.StudentName)

Html:

Steve

10.1 Label

Razor:

@Html.Label("StudentName")
@Html.Label("StudentName","Student-Name")

Html:

<label for="StudentName">姓名</label>
<label for="StudentName">Student-Name</label>

10.2 LabelFor

Razor:

@model Student

@Html.LabelFor(m => m.StudentName)

Html:

<label for="StudentName">姓名</label>

11.1 Editor

該擴展方法是一種基於數據類型生成html輸入元素的方法。Editor()或EditorFor()擴展方法基於Model對象的屬性的數據類型生成html標簽。

數據類型 Html標簽
string <input type="text" >
int <input type="number" >
decimal, float <input type="text" >
boolean <input type="checkbox" >
Enum <input type="text" >
DateTime <input type="datetime" >

Razor:

StudentId:      @Html.Editor("StudentId")
Student Name:   @Html.Editor("StudentName")
Age:            @Html.Editor("Age")
Password:       @Html.Editor("Password")
isNewlyEnrolled: @Html.Editor("isNewlyEnrolled")
Gender:         @Html.Editor("Gender")
DoB:            @Html.Editor("DoB")

Html:

11.2EditorFof

Razor:

StudentId:      @Html.EditorFor(m => m.StudentId)
Student Name:   @Html.EditorFor(m => m.StudentName)
Age:            @Html.EditorFor(m => m.Age)
Password:       @Html.EditorFor(m => m.Password)
isNewlyEnrolled: @Html.EditorFor(m => m.isNewlyEnrolled)
Gender:         @Html.EditorFor(m => m.Gender)
DoB:            @Html.EditorFor(m => m.DoB)

Html:

12 Form

Razor:

  @using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @class = "form" }))
    {
        
    }

Html:

<form action="/ControllerName/ActionName" class="form" method="post">       
     
</form>

13.1 Html.Action() 執行一個Action,並返回html字符串。

如:

Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)

返回:

<a href="/somecontroller/someaction/123">link text</a>

13.3 Url.Action() 返回一個Action的鏈接地址

如:

Url.Action("someaction", "somecontroller", new { id = "123" })

返回:

/somecontroller/someaction/123


自定義Helper擴展方法

您還可以通過在HtmlHelper類上創建擴展方法或在類中創建靜態方法來創建自定義Helper方法。

    public static class CustomHelpers
    {
     //Submit Button Helper
     public static MvcHtmlString SubmitButton(this HtmlHelper helper, string 
     buttonText)
     {
     string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
     return new MvcHtmlString(str);
     }
     //Readonly Strongly-Typed TextBox Helper
     public static MvcHtmlString TextBoxFor<TModel, TValue>(this 
     HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>>
     expression, bool isReadonly)
     {
     MvcHtmlString html = default(MvcHtmlString);
     
     if (isReadonly)
     {
     html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
     expression, new { @class = "readOnly",
     @readonly = "read-only" });
     }
     else
     {
     html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
     expression);
     }
     return html;
     }
    }

以上就是HtmlHelper的一些常用擴展方法。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM