自定义标签助手中 <input asp-for='files' /> 的问题

problem by <input asp-for='files' /> in Custom tag helper

我创建了一个自定义 tagHelper。 但是我在开发显示的代码片段时遇到了一个问题(输入asp-for="files" 正好传送到浏览器)。

public override void Process(TagHelperContext context, TagHelperOutput output){
var form = @"<form id='uploadFileForm' method='post' enctype='multipart/form-data'  >
        <input asp-for='files' />
        <input type = 'button' id ='btnUpload' value =' upload' />
        </form > ";
output.PreContent.AppendHtmlLine(form);}

和我的模特:

[Required(ErrorMessage = "Please select a file.")]
[DataType(DataType.Upload)]
public IList<IFormFile> files { get; set; }

更多说明:使用时

<input asp-for='files' />

在一个视图中,最终生成如下代码 浏览器:

<input type="file" data-val="true" data-val-required="Please select a file." id="files" multiple="multiple" name="files" />

现在,我不知道要在 tagHelper 中做什么才能通过 taghelper 在上面的行中生成相同的输出。 请帮助我

看文档(版本不对换版本):https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/authoring?view=aspnetcore-2.2

从那里的例子中收集,你要找的应该是这样的 (未经测试的示例):

public override void Process(TagHelperContext context, TagHelperOutput output){

    // Should already be input, but in case you want to change it to something else
    output.TagName = "input";

    // remove the old attribute
    // You probably need to do something different if you want to carry over the attribute
    output.Attributes.RemoveAll("asp-for");      

    output.Attributes.SetAttribute("type", "file");
    output.Attributes.SetAttribute("data-val", "true");
    output.Attributes.SetAttribute("data-val-required", "Please select a file.");
    output.Attributes.SetAttribute("id", "files");
    output.Attributes.SetAttribute("multiple", "multiple");
    output.Attributes.SetAttribute("name", "files");
}



我不确定您是否真的可以将它用于预定义标签(如输入),如果您创建自定义标签(尚不存在的东西)可能会更好。

由于您还没有为您使用的注释发布任何示例,假设您将其更改为:

<custominput asp-for='files' />

那你的TagHelper上应该有这样的东西吧Class.

[HtmlTargetElement("custominput", TagStructure = TagStructure.WithoutEndTag)] 



上面的示例忽略了您的模型,所以我假设如果您想使用它,您需要以某种方式将它提供给您的 TagHelper Class,并相应地更改 SetAttribute 行。