@Html.DisplayFor 的 MVC6 替代品 [英] MVC6 alternative to @Html.DisplayFor
本文介绍了@Html.DisplayFor 的 MVC6 替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
MVC6 引入了 Tag Helper,与使用 @Html.EditorFor 等相比,这是一种更好的方法.但是我还没有找到任何可以替代 @Html.DisplayFor 的 Tag Helper.
MVC6 introduces Tag Helpers which is a better way compared to using @Html.EditorFor, etc. However I have not found any Tag Helper that would be an alternative to @Html.DisplayFor.
当然,我可以直接在 Razor 页面上使用变量,例如 @Model.BookingCode.但这不允许控制格式.
Of course I can use a variable directly on a Razor page, such as @Model.BookingCode. But this does not allow to control formatting.
对于 MVC6,显示模型属性值的概念正确方法是什么?
With MVC6, what's conceptually correct way for displaying a value of a model property?
推荐答案
您可以创建自己的标签助手
You can create your own tag helper
namespace MyDemo.TagHelpers
{
[HtmlTargetElement("p", Attributes = ForAttributeName)]
public class DisplayForTagHelper : TagHelper
{
private const string ForAttributeName = "asp-for";
[HtmlAttributeName(ForAttributeName)]
public ModelExpression For { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
var text = For.ModelExplorer.GetSimpleDisplayText();
output.Content.SetContent(text);
}
}
}
在视图中添加使用它:
<p asp-for="MyProperty" class="form-control-static"></p>
这篇关于@Html.DisplayFor 的 MVC6 替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文