4
I’m trying to write a Htmlhelper and seeing some basic examples I found one with the class TagBuilder
that already helping:
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));
}
}
}
Only that I wish to create a larger facilitator, in order to manipulate a value that will be displayed, some classes css
etc. Soon, I would not like to have to rewrite a whole helper
which already exists as the TextBoxFor
or the EditorFor
.
Starting from that will, so I thought I could reuse these helpers and add my manipulations.
Here’s what I was thinking about doing:
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 the TagBuilder
doesn’t work that way.
Manipulating something ready helps by not having to rewrite things the framework already does, such as generating the id and name of the element among others.
How can I solve this? What would be a more practical way?
Just remembering that this code is tested and worked at least in my tests I do not know if something happened keep informed... vlw @Tiagosilva
– user6026