0

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 " />

2
  • 1
    You would need to write you own customTagHelper which uses reflection to read the value of the DataType enum to add the class Commented Feb 4, 2018 at 21:54
  • 2
    i created a nuget to help with such things. you can check this: netcoresimple.azurewebsites.net/docs/Generator You can use a generator and create a custom razor template. The template is strongly typed and you can easily access the datatype Commented Feb 4, 2018 at 23:10

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.