As Stephen Muecke suggested, you'll need to write a TagHelper for this. The TagHelper architecture will provide you with all you need.
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace AnnotationBasedAttributes
{
[HtmlTargetElement("input")]
public class MyAwesomeTagHelper : TagHelper
{
public ModelExpression AspFor { get; set; }
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
if (!(this.AspFor.Metadata is DefaultModelMetadata modelMetadata))
{
return Task.CompletedTask;
}
var dataTypeAttribute = modelMetadata.Attributes.Attributes.OfType<DataTypeAttribute>().FirstOrDefault();
if (dataTypeAttribute == null)
{
return Task.CompletedTask;
}
var type = dataTypeAttribute.DataType.ToString().ToLower();
output.Attributes.Add(new TagHelperAttribute("class", type));
return Task.CompletedTask;
}
}
}
You don't need to do anything special in your view. Just use the input tag helper as usual:
@model IndexModel
<label asp-for="Amount"></label>
<input asp-for="Amount" />
Just don't forget to tell your app to search for TagHelpers in your assembly. Do this in _ViewImports.cshtml:
@addTagHelper *, MyWebApplication
TagHelperwhich uses reflection to read the value of theDataTypeenum to add the class