Reputation: 15999
How can I add a attribute to a <input />
tag based on the DataType using razor.
For instance if my data does have annotation
[DataType(DataType.Currency)]
public float Amount {get; set;}
Then I would like to have <input name="Amount" class="currency" >
when using the tag helper <input asp-for="Amount " />
Upvotes: 0
Views: 895
Reputation: 489
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
Upvotes: 1