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