问题
Is there a way to build the custom Html Helpers and put them into sub-sections? I.e:
@Html.Buttons.Gray
@Html.Buttons.Blue
@Html.Tables.2Columns
@Html.Tables.3Columns
Thanks.
回答1:
Helpers are simply extension methods. So you could create helpers that return object that allow you to chain method calls, e.g. @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};
}
}
回答2:
I don't think you can do it like that. Create an enum and then use that to reference colors, like so:
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);
}
}
You could do the same type of thing for the table, but this should give you the general idea. It's a normal helper extension method, but takes an enum val as the parameter to give you the desired end result.
回答3:
If you want to avoid Buttons() being a function, see http://haacked.com/archive/2011/02/21/changing-base-type-of-a-razor-view.aspx for how to accomplish something like this by creating a custom HtmlHelper: @MyAppHtml.Buttons.Gray
You might be able to instead override HtmlHelper instead if you strictly want @Html.Buttons.Gray
来源:https://stackoverflow.com/questions/9298990/razor-htmlhelpers-with-sub-sections