Custom Asp.net MVC 3 editor template not getting used
Asked Answered
S

1

10

I have an MVC 3 web app that uses Razor view engine. I would like to extend default editor templates so I'd like to add additional HTML5 attributes to input elements like autofocus.

I'm using AdditionalMetadataAttribute to specify certain properties on my entity to be autofocus:

public class MyEntity
{
    public int Id { get; set; }

    [Required]
    [AdditionalMetadata("autofocus", true)]
    [DataType(DataType.Text)]
    public string Name { get; set; }

    ...
}

Since view scaffolding uses EditorFor method I decided to play along and wanted to override default String.cshtml template so that it would also add any additional metadata as attributes. To play along means that I don't want to use TextBoxFor where I can control input's attributes.

This is my slightly changes String.cshtml that adds all additional metadata attributes as input HTML attributes:

@{
    // System.Diagnostics.Debugger.Break();
    this.ViewData.ModelMetadata.AdditionalValues.Add("class", "text-box single-line");
}
@Html.TextBox(string.Empty, ViewContext.ViewData.TemplateInfo.FormattedModelValue, this.ViewData.ModelMetadata.AdditionalValues)

This template should render the same input type=text with the same CSS classes but also with additional attributes if any of them are provided.

I then put this file in the ~/Views/Shared/EditorTemplates/ folder but it seems this template never gets picked up, because all I get is just the default input text box.

What am I doing wrong?

Seanseana answered 3/2, 2012 at 22:21 Comment(1)
just curious if there was a particular reason to use [DataType(DataType.Text)]?Clarindaclarine
R
15

Your String.cshtml editor template is never because of the following attribute: [DataType(DataType.Text)] that you used to decorate your model property with.

This uses the ~/Views/Shared/EditorTemplates/Text.cshtml template.

Rockingham answered 4/2, 2012 at 20:59 Comment(3)
Thanks Darin. I was just getting back to SO because I found out the same thing. Renaming it or removing that particular declarative attribute actually does make it work. Thanks anyway.Seanseana
One more Q: I would like to consolidate two editor templates (Text and String) by not repeating code so I would like to reference one inside of the other (Text should just use String). I used @Html.Partial("~/Views/Shared/EditorTemplates/String.cshtml") but I get an error: The partial view '~/Views/Shared/EditorTemplates/String.cshtml' was not found or no view engine supports the searched locations.Seanseana
Thanks mate... It was actually a typo yes... Because I have these templates only in one particular area. :) I obviously need some vacation. :) Thanks again.Seanseana

© 2022 - 2024 — McMap. All rights reserved.