在vanilla HTML Helpers中,我通常使用<div>@Model.Name</div>
来打印Name
属性,Tag Helpers是否有类似的功能?
答案 0 :(得分:1)
正如我在评论中所说的那样,没有一个标准的标签帮助器可以生成一个div(或者不管我上次看的是什么)。这是我们在办公室写的一个标签助手的例子,用来生成一个div:
[HtmlTargetElement("div", Attributes = FOR_ATTRIBUTE_NAME)]
public class DivTagHelper : TagHelper
{
private const string FOR_ATTRIBUTE_NAME = "si-for";
/// <summary>
/// Creates a new <see cref="DivTagHelper"/>.
/// </summary>
/// <param name="generator">The <see cref="IHtmlGenerator"/>.</param>
public DivTagHelper(IHtmlGenerator generator)
{
Generator = generator;
}
[HtmlAttributeNotBound]
[ViewContext]
public ViewContext ViewContext { get; set; }
protected IHtmlGenerator Generator { get; }
/// <summary>
/// An expression to be evaluated against the current model.
/// </summary>
[HtmlAttributeName(FOR_ATTRIBUTE_NAME)]
public ModelExpression For { get; set; }
/// <inheritdoc />
/// <remarks>Does nothing if <see cref="For"/> is <c>null</c>.</remarks>
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = output.Content.IsModified ? output.Content.GetContent() :
(await output.GetChildContentAsync()).GetContent();
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
output.TagName = "div";
string content;
if (For.Metadata.UnderlyingOrModelType == typeof(bool))
{
content = ((bool?) For.Model).ToYesNo();
}
else
{
var displayFormatString = For.ModelExplorer.Metadata.DisplayFormatString;
content = string.IsNullOrEmpty(displayFormatString)
? For.Model?.ToString()
: string.Format(displayFormatString, For.Model);
}
// Honour the model's specified format if there is one.
output.Content.SetContent(content);
output.PostContent.SetHtmlContent(childContent);
}
}
这是一个用法示例:
<li class="TypeFile">
<si-label si-for="FileSize"></si-label>
<div si-for="FileSize" id="FileSize" class="ReadOnlyValue"></div>
<input class="subForm" asp-for="FileSizeInBytes" />
</li>
请注意,“si”前缀是我们公司的首字母,以确保不存在与现有属性的歧义。
这是一个输出样本:
<li class="TypeFile">
<label for="FileSize">File Size:</label>
<div id="FileSize" class="ReadOnlyValue">13.700KB</div>
<input class="subForm" type="hidden" id="FileSizeInBytes" name="FileSizeInBytes" value="14029" />
</li>
答案 1 :(得分:0)
您可以将标准结构用于您的任务:
<input asp-for="Name" class="form-control" />