承接前文,我們正式進入 HtmlHelper 擴充方法的建構階段。以 HtmlText 類別為例,展示如何設計靈活的多載方法組,滿足不同使用情境。
public static class HtmlHelperExtensions
{
#region Textbox
public static IViewObject NewText(this HtmlHelper htmlHelper, string name)
{
return NewText(htmlHelper, name, null);
}
public static IViewObject NewText(this HtmlHelper htmlHelper, string name, string labelText)
{
return NewText(htmlHelper, name, labelText, null);
}
public static IViewObject NewText(this HtmlHelper htmlHelper, string name, string labelText, object value)
{
return NewText(htmlHelper, name, labelText, value, null, false, true, null);
}
public static IViewObject NewText(
this HtmlHelper htmlHelper,
string name,
string labelText,
object value,
string validationMessage,
bool @readonly,
bool createLi,
object attributes)
{
IViewObject viewObject = new HtmlText(
new ViewRequestContext(htmlHelper),
name,
labelText,
value,
validationMessage,
@readonly,
createLi,
attributes);
viewObject.StartView();
return viewObject;
}
#endregion
// NOTE: 此處省略其他 Helper 的擴充方法...
}
IViewObject:確保所有 Helper 都能搭配 using 區塊使用,擁有完整的生命週期管理。ViewRequestContext:封裝 HtmlHelper 所需的上下文資訊,降低耦合。這樣的設計模式不僅適用於 TextBox,同樣可套用至 DropDownList、CheckBox、RadioButton 等各類表單元件,打造一致性的開發體驗。