如何在TagHelper.Process中获取属性属性类型?

时间:2018-04-06 22:01:42

标签: c# asp.net-core asp.net-core-tag-helpers

我编写了一个标记帮助器,我需要获取Model的属性类型,因为我想基于它创建一个html标签的实例。

如果它的类型是Boolean,我想创建Checkbox的实例,依此类推。

[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" });
        }
    }
}
  

更新

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>

(如果您通过PropertyInfo传递属性列表(ViewData列表)进行查看,则无法访问EditTagHelper.cs中的模型值,或者至少我无法访问!因此我通过ViewDataViewData["PropertyList"]))

传递了属性名称

1 个答案:

答案 0 :(得分:0)

ModelExplorerModelType,其中包含模型的类型:

var typeOfProperty = modelExProp.ModelType;

您还可以通过调用Object.GetType()直接从其值获取属性类型:

var typeOfProperty = propValue?.GetType();