gpt4 book ai didi

c# - 嵌入在另一个标签助手代码中的标签助手不呈现

转载 作者:行者123 更新时间:2023-11-30 15:56:06 25 4
gpt4 key购买 nike

我正在尝试使用 .net Core 2.0 中的以下自定义标签助手来简化长表单的创建:

@model ObApp.Web.Models.ViewComponents.FormFieldViewModel

<span>Debug - Paramater value: @Model.FieldFor</span>
<div class="form-group">
<label asp-for="@Model.FieldFor"></label>
<input asp-for="@Model.FieldFor" class="form-control" />
</div>

这看起来很简单,但是当我使用时我得到了意想不到的结果:

<vc:form-field field-for="PersonEmail"></vc:form-field>

预期结果

<span>Debug - Paramater value: PersonEmail</span>
<div class="form-group">
<label for="PersonEmail">Email</label>
<input name="PersonEmail" class="form-control" id="PersonEmail"
type="text" value="PersonEmail">
</div>

实际结果

<span>Debug - Paramater value: PersonEmail</span>
<div class="form-group">
<label for="FieldFor">FieldFor</label>
<input name="FieldFor" class="form-control" id="FieldFor"
type="text" value="PersonEmail">
</div>

我已经尝试从 @Model.FieldFor 周围删除引号,以及一些其他语法更改。

有什么建议吗?

谢谢!

最佳答案

正如其他人向我指出的那样,可能无法按照我发布此问题时最初希望的方式直接嵌入标签助手。因此,我重构了代码,改为以编程方式“更新”所需的标签助手。

我的最终解决方案比我预期的要多得多,但从长远来看,它将节省大量时间来开发我计划的表单密集型应用程序。

目标

我的目标是通过使用这个自定义标签助手来加速表单的创建,例如:

<formfield asp-for="OrganizationName"></formfield>

要生成这些内置的 Razor 标签助手:

<div class="form-group">
<div class="row">
<label class="col-md-3 col-form-label" for="OrganizationName">Company Name</label>
<div class="col-md-9">
<input name="OrganizationName" class="form-control" id="OrganizationName" type="text" value="" data-val-required="The Company Name field is required." data-val="true" data-val-maxlength-max="50" data-val-maxlength="Maximum company name length is 50 characters.">
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="OrganizationName"></span>
</div>
</div>
</div>

我最初的工作解决方案

这是针对简单案例的首轮测试解决方案。 IE。对于默认的硬编码类和文本框输入类型。

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ObApp.Web.TagHelpers
{
// Builds form elements to generate the following (for example):
// <div class="form-group">
// <div class="row">
// <input ... >Email</input>
// <div>
// <input type="text" ... />
// <span class="field-validation-valid ... ></span>
// </div>
// </div>
// </div>

public class FormfieldTagHelper : TagHelper
{
private const string _forAttributeName = "asp-for";
private const string _defaultWraperDivClass = "form-group";
private const string _defaultRowDivClass = "row";
private const string _defaultLabelClass = "col-md-3 col-form-label";
private const string _defaultInputClass = "form-control";
private const string _defaultInnerDivClass = "col-md-9";
private const string _defaultValidationMessageClass = "";

public FormfieldTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}

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

public IHtmlGenerator Generator { get; }

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

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
// Replace this parent tag helper with div tags wrapping the entire form block
output.TagName = "div";
output.Attributes.SetAttribute("class", _defaultWraperDivClass);

// Manually new-up each child asp form tag helper element
TagHelperOutput labelElement = await CreateLabelElement(context);
TagHelperOutput inputElement = await CreateInputElement(context);
TagHelperOutput validationMessageElement = await CreateValidationMessageElement(context);

// Wrap input and validation with column div
IHtmlContent innerDiv = WrapElementsWithDiv(
new List<IHtmlContent>()
{
inputElement,
validationMessageElement
},
_defaultInnerDivClass
);

// Wrap all elements with a row div
IHtmlContent rowDiv = WrapElementsWithDiv(
new List<IHtmlContent>()
{
labelElement,
innerDiv
},
_defaultRowDivClass
);

// Put everything into the innerHtml of this tag helper
output.Content.SetHtmlContent(rowDiv);
}

private async Task<TagHelperOutput> CreateLabelElement(TagHelperContext context)
{
LabelTagHelper labelTagHelper =
new LabelTagHelper(Generator)
{
For = this.For,
ViewContext = this.ViewContext
};

TagHelperOutput labelOutput = CreateTagHelperOutput("label");

await labelTagHelper.ProcessAsync(context, labelOutput);

labelOutput.Attributes.Add(
new TagHelperAttribute("class", _defaultLabelClass));

return labelOutput;
}

private async Task<TagHelperOutput> CreateInputElement(TagHelperContext context)
{
InputTagHelper inputTagHelper =
new InputTagHelper(Generator)
{
For = this.For,
ViewContext = this.ViewContext
};

TagHelperOutput inputOutput = CreateTagHelperOutput("input");

await inputTagHelper.ProcessAsync(context, inputOutput);

inputOutput.Attributes.Add(
new TagHelperAttribute("class", _defaultInputClass));

return inputOutput;
}

private async Task<TagHelperOutput> CreateValidationMessageElement(TagHelperContext context)
{
ValidationMessageTagHelper validationMessageTagHelper =
new ValidationMessageTagHelper(Generator)
{
For = this.For,
ViewContext = this.ViewContext
};

TagHelperOutput validationMessageOutput = CreateTagHelperOutput("span");

await validationMessageTagHelper.ProcessAsync(context, validationMessageOutput);

return validationMessageOutput;
}

private IHtmlContent WrapElementsWithDiv(List<IHtmlContent> elements, string classValue)
{
TagBuilder div = new TagBuilder("div");
div.AddCssClass(classValue);
foreach(IHtmlContent element in elements)
{
div.InnerHtml.AppendHtml(element);
}

return div;
}

private TagHelperOutput CreateTagHelperOutput(string tagName)
{
return new TagHelperOutput(
tagName: tagName,
attributes: new TagHelperAttributeList(),
getChildContentAsync: (s, t) =>
{
return Task.Factory.StartNew<TagHelperContent>(
() => new DefaultTagHelperContent());
}
);
}
}
}

后续步骤/改进建议

这适用于没有验证错误的文本框。调整默认 CSS 后,我计划采取的后续步骤是:

  1. 在出现验证错误时显示用于格式设置的正确 CSS 类属性。此时标签助手将为我“工作”。
  2. 将硬编码的 CSS 类移到站点配置文件中。
  3. 绑定(bind)到 View 中的 HTML 属性以允许传入非默认类。另一种方法是通过 ViewModel 传入非默认表单类。
  4. 检测非文本框输入类型并相应地设置格式。

感谢@Chris Pratt 让我开始朝着正确的方向前进。

关于c# - 嵌入在另一个标签助手代码中的标签助手不呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47547844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com