2014-02-24 40 views
0

我想要一套Razor助手來生成表單輸入。我希望助手有一個可鏈接的API,允許從多個上下文(在一個表單組中,作爲獨立的輸入)調用表單輸入,並且具有幾個可定製的屬性(值,佔位符,類等)。我做不是想要實現100+方法重載來實現我的目標。Chainable Razor Helper API

實例API:

@Html.TextField("Test Text") 
    @Html.TextField("PhoneNumber").Placeholder("555-555-5555") 
    @Html.TextField("FirstName").Value("Gilbert") 
    @Html.TextField("LastName").Value("Grape").Placeholder("Last Name Here") 

我有一個支持這個語法的實現,但恐怕它依賴於一個黑客才能發揮作用。請檢查這個實現,並告訴我,如果我犯了一個錯誤。感興趣的部分是在ChainableTextField.ToString()

public static class HtmlFormExtensions 
{ 
    public static ChainableTextField TextField(this HtmlHelper html, string name) 
    { 
     return new ChainableTextField(html.ViewContext.Writer,name); 
    } 

    public class ChainableTextField 
    { 
     private readonly TextWriter _writer; 
     private readonly TagBuilder _tagBuilder; 

     public ChainableTextField(TextWriter writer, string name) 
     { 
      _writer = writer; 
      _tagBuilder = new TagBuilder("input"); 
      _tagBuilder.Attributes["name"] = name; 
      _tagBuilder.Attributes["type"] = "text"; 
     } 

     public ChainableTextField Value(string value) 
     { 
      _tagBuilder.Attributes["value"] = value; 
      return this; 
     } 

     public ChainableTextField Placeholder(string placeHolder) 
     { 
      _tagBuilder.Attributes["placeholder"] = placeHolder; 
      return this; 
     } 

     public override string ToString() 
     { 
      _writer.WriteLine(_tagBuilder.ToString(TagRenderMode.SelfClosing)); 
      return ""; 
     } 
    } 
} 

的 「黑客」 是

public override string ToString() 
{ 
    _writer.WriteLine(_tagBuilder.ToString(TagRenderMode.SelfClosing)); 
    return ""; 
} 

它是不好的做法,以做到這一點?如果我使用這種技術,我會遇到麻煩嗎?

+0

哪一點特別是黑客? –

+0

我更新了這個問題,並澄清了我認爲的黑客行爲 –

回答

4

IHtmlString接口是專門爲此設計的。所以你寧願讓你的ChainableTextField類實現這個接口,而不是覆蓋ToString方法。這樣,您不再需要將TextWriter傳遞給此類的構造函數。

+0

因此,通過IHtmlString,我可以生成一個'ChainableTextField',然後在最終顯示之前(可選擇使用Placeholder()或Value()它? –

+0

啊,我的確可以!謝謝。我懷疑有這樣的事情 –

相關問題