OjM*_*OjM 8 c# razor asp.net-core asp.net-core-tag-helpers
我想将输入标记助手与剃刀代码组合起来设置属性,但我不能让这两种技术一起工作.我只是试图根据视图模型属性的值在输入字段上设置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的禁用类.
有没有办法让这项工作?
Shy*_*yju 13
要呈现禁用的输入元素,只需添加禁用的属性即可.以下所有内容将呈现禁用的输入文本元素.
<input type="checkbox" disabled />
<input type="checkbox" disabled="disabled" />
<input type="checkbox" disabled="false" />
<input type="checkbox" disabled="no" />
<input type="checkbox" disabled="enabled" />
<input type="checkbox" disabled="why is it still disabled" />
Run Code Online (Sandbox Code Playgroud)
在Asp.NET Core中,您可以扩展现有的输入标记帮助程序以创建只读输入标记帮助程序.
扩展InputTagHelper
类,添加新属性以标识是否应禁用输入,并根据此值将"disabled"属性添加到输入.
[HtmlTargetElement("input", Attributes = ForAttributeName)]
public class MyCustomTextArea : InputTagHelper
{
private const string ForAttributeName = "asp-for";
[HtmlAttributeName("asp-is-disabled")]
public bool IsDisabled { set; get; }
public MyCustomTextArea(IHtmlGenerator generator) : base(generator)
{
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (IsDisabled)
{
var d = new TagHelperAttribute("disabled", "disabled");
output.Attributes.Add(d);
}
base.Process(context, output);
}
}
Run Code Online (Sandbox Code Playgroud)
现在要使用这个自定义textarea助手,你需要调用该addTagHelper
方法_ViewImports.cshtml
.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, YourAssemblyNameHere
Run Code Online (Sandbox Code Playgroud)
现在在您的视图中,您可以指定asp-is-disabled
属性值.
<input type="text" asp-for="OtherDrugs"
asp-is-disabled="@Model.OtherDrugs==null"/>
Run Code Online (Sandbox Code Playgroud)