我按照一些指南为ASP Core创建了自定义标记帮助程序.
这是我的帮手:
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
namespace ToolControlSystem.TagHelpers
{
[HtmlTargetElement("description", Attributes = DescriptionAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)]
public class DescriptionTagHelper : TagHelper
{
private const string DescriptionAttributeName = "asp-for";
[HtmlAttributeName(DescriptionAttributeName)]
public ModelExpression Model { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
var description = GetDescription(Model.ModelExplorer);
output.TagName = "span";
output.TagMode = TagMode.StartTagAndEndTag;
output.Content.SetContent(description);
}
private string GetDescription(ModelExplorer modelExplorer)
{
string description;
description = modelExplorer.Metadata.Placeholder;
if (String.IsNullOrWhiteSpace(description))
{
description = modelExplorer.Metadata.Description;
}
return description; …
Run Code Online (Sandbox Code Playgroud) 我理解asp-fallback-*
标签助手的作用.我不明白的是如何.
例如:
<link rel="stylesheet"
href="//ajax.aspnetcdn.com/ajax/bootstrap/3.3.5/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only"
asp-fallback-test-property="position"
asp-fallback-test-value="absolute" />
Run Code Online (Sandbox Code Playgroud)
这将从CDN加载引导程序,并在CDN关闭时加载本地副本.
但它如何决定呢?我认为它会检查asp-fallback-test-class
,asp-fallback-test-property
和asp-fallback-test-value
.但这些属性意味着什么?
如果我想从CDN上挂一些其他的库,我需要为那些提供一些东西,但我不知道该把它放在那里.
有很多这方面的例子,但是我找不到关于它是如何工作的解释.
更新
我并不是真的想了解标签助手的工作原理 - 它们是如何渲染的,等等.我试图了解如何为这些属性选择值.例如,jQuery回退脚本通常具有asp-fallback-test="window.jQuery"
合理意义 - 它是测试jQuery是否已加载的测试.但是我上面展示的那些是完全不同的.如何选择它们?如果我想使用其他一些CDN交付的库,我需要为这些属性指定值...我会用什么?为什么选择那些引导程序?
更新2
要了解回退过程本身的工作原理以及这些标记的编写方式,请参阅@ KirkLarkin的回答.要了解使用这些测试值的原因,请参阅我的回答.
c# razor asp.net-core asp.net-core-tag-helpers asp.net-core-2.1
我一直在关注这篇关于在此处编写自定义标记帮助程序的 Microsoft 文章。
在我看到元素标记在 C# 中硬编码的代码的每个地方
示例(取自上述链接)
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "section";
output.Content.SetHtmlContent(
$@"<ul><li><strong>Version:</strong> {Info.Version}</li>
<li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
<li><strong>Approved:</strong> {Info.Approved}</li>
<li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
output.TagMode = TagMode.StartTagAndEndTag;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法从 cshtml 文件加载标记模板,而不是这样做?(类似于加载部分视图)
我的目的是拥有单独的cshtml
文件(每个元素类型一个),以便我可以轻松地设置它们的样式。我的 C# 看起来也很干净!
谢谢,
詹姆士
有没有办法创建一个标签助手,以某种方式迭代(转发器像)内部标签助手?就是这样的:
<big-ul iterateover='x'>
<little-li value='uses x somehow'></little-li>
</bg-ul>
Run Code Online (Sandbox Code Playgroud)
我知道我可以用razor foreach做到这一点但是试图找出如何做而不必在我的html中切换到c#代码.
我想将输入标记助手与剃刀代码组合起来设置属性,但我不能让这两种技术一起工作.我只是试图根据视图模型属性的值在输入字段上设置disabled属性.
当我把剃刀代码放在asp-for
标签后面时,剃刀智能感知器无法被识别,并且该字段未按预期禁用...
<input asp-for="OtherDrugs" @((Model.OtherDrugs == null) ? "disabled" : "") class="form-control" />
Run Code Online (Sandbox Code Playgroud)
渲染输出......
<input type="text" id="OtherDrugs" name="OtherDrugs" value="" />
Run Code Online (Sandbox Code Playgroud)
当我将剃刀代码放在asp-for
标签之前时,无法识别标签帮助程序intellisense,并且未按预期使用视图模型属性设置该字段...
<input @((Model.OtherDrugs == null) ? "disabled" : "") asp-for="OtherDrug" class="form-control" />
Run Code Online (Sandbox Code Playgroud)
渲染输出......
<input disabled asp-for="OtherDrugs" class="form-control" />
Run Code Online (Sandbox Code Playgroud)
请注意,如果剃刀代码位于类属性中,则组合标记助手和剃刀会起作用.遗憾的是,输入字段需要disabled属性,而不是bootstrap 3的禁用类.
有没有办法让这项工作?
我已将我的asp.net核心Web应用程序从1.0.1更新到1.1.0,但我的viewcomponents的标记帮助程序不起作用:
<vc:login-form />
Run Code Online (Sandbox Code Playgroud)
它输出标签.它使用旧语法:@await Component.InvokeAsync(typeof(LoginFormViewComponent))
的package.json:
{
"title": "DevPortal.Web",
"version": "0.1.0",
"language": "",
"dependencies": {
"Microsoft.NETCore.App": {
"version": "1.1.0",
"type": "platform"
},
"Microsoft.AspNetCore.StaticFiles": "1.1.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
"Microsoft.AspNetCore.Mvc": "1.1.0",
"NuGet.CommandLine": "3.5.0",
},
"tools": {
"Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
"Microsoft.AspNetCore.Razor.Tools": "1.1.0-preview4-final"
},
"frameworks": {
"netcoreapp1.1": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
},
"buildOptions": {
"emitEntryPoint": true,
"preserveCompilationContext": true
},
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true
}
},
"scripts": {
"prepublish": [ "bower install"],
"postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework …
Run Code Online (Sandbox Code Playgroud) c# asp.net-core asp.net-core-tag-helpers asp.net-core-viewcomponent
我下载并安装了最新的.NET Core:
dotnet --version
1.0.0-preview5-004478
Run Code Online (Sandbox Code Playgroud)
我还更新了我的AspNetCore项目的包引用:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.TagHelpers" Version="1.1.0" />
<PackageReference Include="Microsoft.NETCore.App" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Tools" Version="1.1.0-preview4-final" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0-preview4-final" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.1.0-preview4-final" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.0" …
Run Code Online (Sandbox Code Playgroud) 我有一个自定义 TagHelper,它扩展了 OOTB InputTagHelper。我根据与其关联的模型属性上存在的自定义 ValidationAttribute 有条件地向其添加属性。TagHelper.Process
方法中的代码工作正常:
if (this.For.Metadata.ValidatorMetadata.OfType<NumericValidationAttribute>().Any())
{
output?.Attributes.SetAttribute(new TagHelperAttribute("inputmode", "numeric"));
output?.Attributes.SetAttribute(new TagHelperAttribute("pattern", "[0-9]*"));
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在单元测试中。我使用 Net Core MVC 测试存储库中提供的代码编写了其他单元测试:https : //github.com/aspnet/Mvc/blob/master/test/Microsoft.AspNetCore.Mvc.TagHelpers.Test/
...但没有真正指导如何为我要测试的属性创建For
ie ModelExpression
,该属性具有与之关联的 Validation 属性:例如
public class TestModel
{
[NumericValidation(ErrorMessage = "Error message")]
public string Field1 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我希望能够填充For.Metadata.ValidatorMetadata
此 ModelExpression的列表,但我不知道如何。
不起作用的完整单元测试是:
[Fact]
public void CustomInputTagHelperProcess_NumericValidationAttributeOnModelProperty_GeneratesCorrectHtml()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var model = new TestModel
{
Field1 = "cc", …
Run Code Online (Sandbox Code Playgroud) unit-testing validationattribute asp.net-core-mvc asp.net-core-tag-helpers
我试图在html结果中向锚点添加请求查询中的任何内容:
虚构的例子:
用户发出请求(请注意,乐队和歌曲可以是任何内容,我有一条路径来满足此请求:模板:"{band}/{song}"):
http://mydomain/band/song?Param1=111&Param2=222
Run Code Online (Sandbox Code Playgroud)
现在我希望我的锚点将查询字符串部分附加到我的锚点的href.所以我试过这样的事情(注意'asp-all-route-data'):
<a asp-controller="topic" asp-action="topic" asp-route-band="iron-maiden" asp-route-song="run-to-the-hills" asp-all-route-data="@Context.Request.Query.ToDictionary(d=>d.Key,d=>d.Value.ToString())">Iron Maiden - Run to the hills</a>
Run Code Online (Sandbox Code Playgroud)
查询字符串的附加实际上与上面的代码一起使用,但随后结果中丢失了"铁娘子"和"跑到山上".上面的标签助手返回以下内容(注意帮助器如何将请求中的乐队和歌曲镜像到href中,而不是我在asp-route属性中指定的乐队和歌曲):
<a href="http://mydomain/band/song?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>
Run Code Online (Sandbox Code Playgroud)
我希望帮助者得到以下结果:
<a href="http://mydomain/iron-maiden/run-to-the-hills?Param1=111&Param2=2222">Iron Maiden - Run to the hills</a>
Run Code Online (Sandbox Code Playgroud)
看起来当我使用asp-all-route-data时,我在结果中丢失了asp-route-band和asp-route-song值.
有没有人偶然发现了这个?
谢谢
Hooroo
asp.net asp.net-mvc tag-helpers asp.net-core asp.net-core-tag-helpers
我的目标是生成一个预先选定<select>
的某个选择值(<option>
)的下拉列表,因此最终的HTML
应该如下所示:
<select>
<option value = "1">Option1</option>
<option value = "2" selected>Option2</option>
<option value = "3">Option3</option>
</select>
Run Code Online (Sandbox Code Playgroud)
请注意,值为2的选项具有一个selected
属性,表示它将在单击下拉列表之前显示.我不能(并且我想尝试)使用.NET Core Tag Helpers实现这一目标.
这是我的模型(我认为你可以安全地忽略细节):
public class ReportViewModel
{
[Display(Name = "Pick a form")]
public IEnumerable<Form> AvailableForms { get; set; }
public Form SelectedForm { get; set; }
public List<ReportData> FormResponses { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
需要注意的是Form
对象那里只是有Id
和Name
它的属性.
这是我的选择声明:
<label asp-for="SelectedForm.Name" class="form-control-label font-weight-bold"></label>
<select asp-for="SelectedForm.Name"
class="form-control"
onchange ="onFormSelected(this.value)"
asp-items="@(new …
Run Code Online (Sandbox Code Playgroud) asp.net-core ×9
c# ×7
asp.net ×2
asp.net-mvc ×2
razor ×2
model ×1
razorengine ×1
tag-helpers ×1
unit-testing ×1