【发布时间】:2012-03-07 03:00:57
【问题描述】:
有没有办法构建自定义 Html Helpers 并将它们放入子部分?即:
@Html.Buttons.Gray
@Html.Buttons.Blue
@Html.Tables.2Columns
@Html.Tables.3Columns
谢谢。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 razor html-helper
有没有办法构建自定义 Html Helpers 并将它们放入子部分?即:
@Html.Buttons.Gray
@Html.Buttons.Blue
@Html.Tables.2Columns
@Html.Tables.3Columns
谢谢。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3 razor html-helper
Helper 只是简单的扩展方法。因此,您可以创建返回允许您链接方法调用的对象的助手,例如@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};
}
}
【讨论】:
我认为你不能那样做。创建一个枚举,然后使用它来引用颜色,如下所示:
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);
}
}
您可以对表格执行相同类型的操作,但这应该可以让您大致了解。这是一个普通的辅助扩展方法,但需要一个枚举 val 作为参数来为您提供所需的最终结果。
【讨论】:
如果您想避免 Buttons() 成为函数,请参阅 http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx 了解如何通过创建自定义 HtmlHelper 来完成类似的操作:@MyAppHtml.Buttons.Gray
如果您严格要求 @Html.Buttons.Gray,您可以改用 HtmlHelper
【讨论】: