我想要一套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 "";
}
它是不好的做法,以做到這一點?如果我使用這種技術,我會遇到麻煩嗎?
哪一點特別是黑客? –
我更新了這個問題,並澄清了我認爲的黑客行爲 –