Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Html.EditorFor() (and others) inside a custom Html Helper?

Basically, I want an Html helper (something like @Html.MyEditor(m => m.Property)) to produce this:

<div class="editor-label">
    @html.LabelFor(m => m.Property)
</div>
<div class="editor-field">
    @html.EditorFor(m => m.Property)
    @html.ValidationMessageFor(m => m.Property)
</div>

Only problem is that I can't seem to access Html.EditorFor() or any of the other extension methods in side my own helper. Example attempt:

@helper Edit(this System.Web.Mvc.HtmlHelper<Spartacus.ViewModels.NewTaskItemModel> html)
{
    <div class="editor-label">
        @html.LabelFor(m => m.Property)
    </div>
    <div class="editor-field">
        @html.EditorFor(m => m.Property)
        @html.ValidationMessageFor(m => m.Property)
    </div>
}

I also tried the extension method syntax:

public static string DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
    var sb = new StringBuilder();
    sb.AppendLine("<div class=\"editor-label\">");
    sb.AppendLine(html.LabelFor(expression));
    sb.AppendLine("</div>");
    sb.AppendLine("<div class=\"editor-field\">");
    sb.AppendLine(html.EditorFor(expression));
    sb.AppendLine(html.ValidationMessageFor(expression));
    sb.AppendLine("</div>");
    return sb.ToString();
}

in both attempts above, the LabelFor, EditorFor, and ValidationMessageFor throw compile errors ("could not be found").

Anyone know of a way to do this? Thanks in advance!

like image 978
jrizzo Avatar asked Aug 15 '11 18:08

jrizzo


1 Answers

It should work if you have a namespace using for the System.Web.Mvc.Html namespace. The extension methods are defined in this namespace on various static extension classes (e.g. EditorExtensions).

like image 134
Tz_ Avatar answered Oct 20 '22 20:10

Tz_