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?

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404

1 Answers1

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 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. – Robert Koritnik Feb 04 '12 at 22:21
  • 2
    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.* – Robert Koritnik Feb 05 '12 at 10:11
  • 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. – Robert Koritnik Feb 05 '12 at 10:31