Search code examples
c#asp.net-coreasp.net-core-tag-helpers

How to get type of property attributes in TagHelper.Process?


I wrote a tag helper and I need to get type of the property of the Model because I want to create an instance of html tag based on it.

If type of it is Boolean, I want to make instance of Checkbox and so on.

[HtmlTargetElement("edit")]
public class EditTagHelper : TagHelper
{
    [HtmlAttributeName("asp-for")]
    public ModelExpression aspFor { get; set; }

    [ViewContext]
    [HtmlAttributeNotBound]
    public ViewContext ViewContext { get; set; }

    protected IHtmlGenerator _generator { get; set; }

    public EditTagHelper(IHtmlGenerator generator)
    {
        _generator = generator;
    }

public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        TagBuilder instance = new TagBuilder("div");
        var propName = aspFor.ModelExplorer.Model.ToString();

        var modelExProp = aspFor.ModelExplorer.Container.Properties.Single(x => x.Metadata.PropertyName.Equals(propName));
        var propValue = modelExProp.Model;
        var propEditFormatString = modelExProp.Metadata.EditFormatString;

        var label = _generator.GenerateLabel(ViewContext, aspFor.ModelExplorer,
            propName, propName, new { @class = "col-md-2 control-label", @type = "email" });

        var typeOfProperty = // HOW CAN I GET TYPE OF PROPERTY ???;
        if (typeOfProperty == typeof(Boolean))
        {
            bool isChecked = propValue.ToString().ToLower() == "true";
            instance = _generator.GenerateCheckBox(ViewContext, aspFor.ModelExplorer, propName, isChecked, new { @class = "form-control" });
        }
    }
}

Updated:

UsersControll:

   [HttpGet]
    public IActionResult Edit(string id)
    {
        var propertyNames = new List<string>();
        var userProperties = typeof(User).GetProperties();

        foreach (PropertyInfo prop in userProperties)
        {
            Type type = prop.PropertyType;
            if (!(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ICollection<>)))
            {
                string attrName = string.Empty;
                var attribute = (DisplayNameAttribute)prop.GetCustomAttribute(typeof(DisplayNameAttribute), true);
                if (attribute != null)
                {
                    attrName = attribute.DisplayName;
                }
                else
                {
                    attrName = prop.Name;
                }

                propertyNames.Add(attrName);
            }
        }
        ViewData["PropertyList"] = propertyNames;

        try
        {
            if (string.IsNullOrEmpty(id))
            {
                return RedirectToAction("Index", "Users");
            }
            User user = _userManager.Users.FirstOrDefault(u => u.Id == int.Parse(id));
            return View(user);
        }
        catch (Exception)
        {
            throw;
        }
    }

Edit.cshtml:

@using System.ComponentModel
@using System.Reflection
@using Jahan.Beta.Web.App.Models.Identity
@using Jahan.Beta.Web.App.Infrastructure
@model Jahan.Beta.Web.App.Models.Identity.User

<div class="row">
@using (Html.BeginForm())
{
    var propertyNames = (List<string>)ViewData["PropertyList"];

    foreach (string item in propertyNames)
    {
        <edit asp-for="@item"></edit>
    }
    <input type="submit" value="Submit" />
}
</div>

(If you pass the list of properties(list of PropertyInfo) by ViewData to view, you cannot access to values of the model in EditTagHelper.cs or at least I couldn't do it! For this reason I passed the name of properties by ViewData (ViewData["PropertyList"]))


Solution

  • ModelExplorer has ModelType which holds the type of the model:

    var typeOfProperty = modelExProp.ModelType;
    

    You could also get property type directly from its value by calling Object.GetType():

    var typeOfProperty = propValue?.GetType();