2012-02-15 69 views
1

有沒有辦法構建自定義的Html Helpers並將其放入子節中? I.e:剃刀HtmlHelpers與子部分?

@Html.Buttons.Gray 
@Html.Buttons.Blue 
@Html.Tables.2Columns 
@Html.Tables.3Columns 

謝謝。

回答

1

助手只是擴展方法。因此,您可以創建返回對象的幫助程序,以便您鏈接方法調用,例如@Html.Button("Text").Grey()

public ButtonHelper 
{ 
    public string Text {get; set;} 
    public MvcHtmlString Grey() 
    { 
     return MvcHtmlString.Create("<button class='grey'>"+ Text +"</button>"); 
    } 
} 

public static class Buttons 
{ 
    public static ButtonHelper Button(this HtmlHelper, string text) 
    { 
     return new ButtonHelper{Text = text}; 
    } 
} 
+0

很好用!謝謝。 – Saxman 2012-02-15 23:53:51

1

我不認爲你可以這樣做。創建一個枚舉,然後用它來引用的顏色,就像這樣:

public enum ButtonColor 
{ 
    Blue = 0x1B1BE0, 
    Gray = 0xBEBECC 
}; 

public static class Extensions 
{ 
    public static MvcHtmlString Button(this HtmlHelper htmlHelper, string Value, ButtonColor buttonColor) 
    { 
     string renderButton = 
      string.Format(
       @"<input type=""button"" value=""{0}"" style=""background-color: {1}"" />", 
       Value, 
       buttonColor.ToString() 
      ); 

     return MvcHtmlString.Create(renderButton); 
    } 
} 

你可以爲表做同樣類型的事情,但是這應該給你的總體思路。這是一個普通的幫助器擴展方法,但將enum val作爲參數來給出所需的最終結果。