2012-02-15 80 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作为参数来给出所需的最终结果。