3

Is there an accepted way to render an EditorTemplate using RenderPartial?

I put a lot of work into an EditorTemplate that would use JQuery UI autocomplete to let the user choose from a list of companies. (It uses an HTML helper to ensure the right JS libraries and CSS rules are included in the "right" places in the generated web page.)

While building another page for that same application, I found I wanted to use that template again, outside the model I built the EditorTemplate for.

This code accomplishes the task, but in a way I can only consider a hack.

@using(Html.BeginForm()) {
    ViewData.TemplateInfo.HtmlFieldPrefix = "CompanyName";
    Html.RenderPartial("~/Views/Shared/EditorTemplates/Company.cshtml", string.Empty);
    <input type="submit" value='Filter' />
}

Because I'm not using EditorFor, there is no "name" parameter, so the rendered input field is just the HtmlFieldPrefix of "CompanyName". The autocomplete works, and I can submit the form and filter the data. But this solution feels sloppy and fragile. Anyone have a better idea?

tereško
  • 58,060
  • 25
  • 98
  • 150
Dave
  • 4,375
  • 3
  • 24
  • 30

1 Answers1

-1

I've moved re-usable "controls" like that to a helper in app_code, and make the editor template a small wrapper, to call the helper.

My editorTemplate for DateTime looks like this:

@model DateTime?
@using System.Globalization
@{
    var name = MvcHtmlString.Create(ViewData.TemplateInfo.GetFullHtmlFieldName(""));
    var id = MvcHtmlString.Create(ViewData.TemplateInfo.GetFullHtmlFieldId(""));
    var value = Model.HasValue && Model.Value > DateTime.MinValue ? string.Format("{0:d}", Model) : "";
}
<span class="edit">
    @Editor.DateTime(id, name, value)
</span>

And I have and Editor.cshtml in app_code that contains:

@helper DateTime(IHtmlString id, IHtmlString name, string value) {
    <input type="text" class="editor-date" id="@id" name="@name" value="@value" />
    if (HttpContext.Current.Items["editor-date"] == null) {
        HttpContext.Current.Items["editor-date"] = new object();

    <script type="text/javascript">
        $(function () {
            $(".editor-date").datepicker({ dateFormat: 'd/m/yy' });
        });
    </script>
    }
}

So I can use my date-editor from EditorFor, or any other way, while including the script to start it only once, and have all code to change on one place.

GvS
  • 52,015
  • 16
  • 101
  • 139
  • Maybe I'm missing something - how does this solve the issue of there being no name parameter because it's not inside a model? (It's not an urgent issue; I ended up creating a model for the page in question, but I'd still love a better method than abusing ViewData.TemplateInfo.HtmlFieldPrefix) – Dave Jan 04 '12 at 16:33