开发者

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 cla开发者_高级运维ss="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!


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜