I'm trying to write an HtmlHelper and seeing some basic examples I found one with the class TagBuilder
already help :
namespace MyNamespace
{
public static class MyHeleprs
{
public static MvcHtmlString Image(this HtmlHelper htmlHelper,
string source, string alternativeText)
{
//declare the html helper
var builder = new TagBuilder("image");
//hook the properties and add any required logic
builder.MergeAttribute("src", source);
builder.MergeAttribute("alt", alternativeText);
//create the helper with a self closing capability
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
}
}
I just want to create a bigger facilitator, in order to manipulate a value that will be displayed, some classes css
etc. So I would not want to rewrite a helper
that already exists as TextBoxFor
or EditorFor
.
Based on this will, I thought about reusing these helpers and adding my manipulations.
I was thinking of doing the following:
public static MvcHtmlString FieldFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
string cssClass = "",
bool placeHolder = false,
bool autoFocus = false,
object htmlAttributes = null)
{
var builder = new TagBuilder(
htmlHelper.TextBoxFor(expression, htmlAttributes).ToString());
// value attribute
...
builder.Attributes["type"] = "text";
builder.Attributes["value"] = value;
// autofocus
if (autoFocus)
builder.Attributes.Add("autofocus", "autofocus");
// css
builder.AddCssClass(cssClass);
// placeholder
...
return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
}
Anyway, highlighting what I thought:
var builder = new TagBuilder(htmlHelper.TextBoxFor(expression, htmlAttributes).ToString());
But TagBuilder
does not work like this.
Manipulating something already ready helps by not having to rewrite things that the framework already does, how to generate the Id and Name of the element among others.
How can I resolve this? What would be a more practical way?