复杂的自定义标签助手

时间:2018-11-20 15:06:09

标签: razor asp.net-core tag-helpers

基本上,我是在扩展先前回答的问题(Updating related entities),以便它是自定义标记帮助程序。

我想向自定义标签助手发送与用户相关的电话列表,并为每个电话生成一个文本框。

因此,假设我具有以下语法:

@Html.EditorFor(model => model.PDFLink, "", new { @class = "form-control setWith", placeholder = "If You want Any.." })

这是我开始使用“自定义标签助手”的信息:

<user-phones phones="@Model.UserPhones" />

public class UserPhonesTagHelper : TagHelper { private readonly IHtmlGenerator _htmlGenerator; private const string ForAttributeName = "asp-for"; public List<UserPhones> Phones { get; set; } [ViewContext] public ViewContext ViewContext { set; get; } [HtmlAttributeName(ForAttributeName)] public ModelExpression For { get; set; } public UserPhonesTagHelper(IHtmlGenerator htmlGenerator) { _htmlGenerator = htmlGenerator; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; output.TagMode = TagMode.StartTagAndEndTag; //output.Attributes.Add("class", "form-group"); StringBuilder sbRtn = new StringBuilder(); for (int i = 0; i < Phones.Count(); i++) { //NEED HELP HERE } output.Content.SetHtmlContent(sbRtn.ToString()); } } 循环中,如何在迭代中生成文本框和与当前“ UserPhone”实体相关的隐藏输入?在发布父剃刀页面时,我还需要保持绑定状态。

我认为这样的方法会有所帮助。但是,我不知道如何将for循环中的ModelExpression传递给方法

for

再次感谢您的帮助...仍在学习asp.net核心。

1 个答案:

答案 0 :(得分:1)

您快到了。

设计

这里的困难是我们需要为未知属性构造一个表达式。假设您想在更高级别使用<user-phones asp-for=""/>,请考虑以下代码:

@model M0

@{
    var M1 = GetM1ByMagic(M0);
}
<user-phones asp-for="@M1.M2....Mx.UserPhones">
</user-phones>

在标签帮助器内,我们可以假定每个属性的默认名称为UserPhones[<index>].<property-name>。但这并非总是这种情况,用户可能希望将其更改为M0.M2....Mx.UserPhones[<index>].<property-name>。但是,不可能知道在编译时将有多少个级别。

因此我们需要一个ExpressionFilter属性将默认表达式转换为目标表达式:

public class UserPhonesTagHelper : TagHelper
{

    [HtmlAttributeName("expression-filter")]
    public Func<string, string> ExpressionFilter { get; set; } = e => e;

    // ...
}

这里的ExpressionFilter是转换表达式字符串的简单委托。

显示代码

我只是复制您的大多数代码并进行一些更改:

public class UserPhonesTagHelper : TagHelper
{
    private readonly IHtmlGenerator _htmlGenerator;
    private const string ForAttributeName = "asp-for";


    public IList<UserPhones> Phones { get; set; }

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

    [HtmlAttributeName(ForAttributeName)]
    public ModelExpression For { get; set; }

    public UserPhonesTagHelper(IHtmlGenerator htmlGenerator)
    {
        _htmlGenerator = htmlGenerator;
    }

    [HtmlAttributeName("expression-filter")]
    public Func<string, string> ExpressionFilter { get; set; } = e => e;

    // a helper method that generate a label and input for some property
    private TagBuilder GenerateSimpleInputForField( int index ,PropertyInfo pi)
    {
        var instance = Phones[index];// current instance of a single UserPhone
        var name = pi.Name;          // property name : e.g. "PhoneNumberId"
        var v = pi.GetValue(instance);

        var div = new TagBuilder("div");
        div.AddCssClass("form-group");

        var expression = this.ExpressionFilter(For.Name + $"[{index}].{name}");
        var explorer = For.ModelExplorer.GetExplorerForExpression(typeof(IList<UserPhones>), o =>v);

        var label = _htmlGenerator.GenerateLabel( ViewContext, explorer, expression, name, new { } );
        div.InnerHtml.AppendHtml(label);

        var input = _htmlGenerator.GenerateTextBox( ViewContext, explorer, expression, v, null, new { @class = "form-control" } );
        div.InnerHtml.AppendHtml(input);
        return div;
    }

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;

        var type = typeof(UserPhones);
        PropertyInfo phoneId= type.GetProperty("UserPhoneId");
        PropertyInfo phoneNumber= type.GetProperty("PhoneNumber");

        for (int i = 0; i< Phones.Count();i++) {
            var div1 = this.GenerateSimpleInputForField(i,phoneId);
            var div2 = this.GenerateSimpleInputForField(i,phoneNumber);

            output.Content.AppendHtml(div1);
            output.Content.AppendHtml(div2);
        }
    }
}
  1. 上方的ProcessAsync()仅显示标签和UserPhoneIdPhoneNumber字段的输入。如果您想自动显示所有属性,只需将方法更改为:

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";
        output.TagMode = TagMode.StartTagAndEndTag;
    
        for (int i = 0; i < Phones.Count(); i++)
        {
            var pis = typeof(UserPhones).GetProperties();
            foreach (var pi in pis)
            {
                var div = this.GenerateSimpleInputForField(i, pi);
                output.Content.AppendHtml(div);
            }
        }
    }
    
  2. 某些字段的默认表达式字符串由以下生成:

    get_the_name_by('asp-for') +'[<index>]'+'<property-name>'  
    

    例如:AppUser.UserPhones[i].<property-name>

    当然,它不适用于所有情况,我们可以自定义expression-filter以根据需要转换表达式:

    // use <user-phones> in view file :
    
    // custom our own expression filter :
    @{
        var regex= new System.Text.RegularExpressions.Regex(@"...");
    
        Func<string, string> expressionFilter = e => {
            var m = regex.Match(e);
            // ...
            return m.Groups["expression"].Value;
        };
    }
    <user-phones phones="@Model.AppUser.UserPhones" 
        asp-for="@Model.AppUser.UserPhones" 
        expression-filter="expressionFilter">
    </user-phones>
    

测试用例

<div class="row">
    @await Html.PartialAsync("_NameAndID", Model.AppUser)
</div>

<form method="post">
    <div class="row">
        <user-phones phones="@Model.AppUser.UserPhones" asp-for="@Model.AppUser.UserPhones" expression-filter="e => e.Substring(8)"></user-phones>
    </div>

    <button type="submit">submit</button>
</form>

第一部分由局部视图生成,第二部分由user-phones生成:

enter image description here