自訂Razor.Helper

自訂Razor.Helper

自訂Razor.Helper

1.專案加入App_Code資料夾

專案 > add > add ASP.NET Folder > App_Code

2.加入檢視

App_Code > add > MVC5 Partial Page (Razor) 

3.編輯定義@helper

@helper Heading5 (string title) 
{
  <h5>@title</h5>
}

4. 一般檢視頁面,呼叫

@helperName.heading5("title_test")

 

擴充Helper

1.加入class

Helper > add > class

2.編寫  ->靜態類別

//靜態HTML  
  public static class Class1
    {
        public static MvcHtmlString Heading51(this HtmlHelper htmlHelper,string title)
        {
            return new MvcHtmlString("<h5>" + title + "</h5>");
        } 
    }

//動態HTML
public static class Class1
    {
        public static MvcHtmlString Heading51(this HtmlHelper htmlHelper,string title)
        {
            TagBuilder builder = new TagBuilder("h1");
            builder.SetInnerText(title);

            return new MvcHtmlString(builder.ToString());
        } 

    }

3.加入using ,使用@Html自訂方法

 @Html.Heading51("test2")

 

 

參考網址:https://ithelp.ithome.com.tw/articles/10160481