MVC6替代@ Html.DisplayFor

时间:2015-09-19 18:10:53

标签: razor asp.net-core-mvc

MVC6引入了Tag Helpers,与使用@ Html.EditorFor等相比,这是一种更好的方式。但是我没有找到任何可以替代@ Html.DisplayFor的Tag Helper。

当然我可以直接在Razor页面上使用变量,例如@ Model.BookingCode。但这不允许控制格式。

使用MVC6,在概念上正确显示模型属性值的方法是什么?

4 个答案:

答案 0 :(得分:12)

@ Html.DisplayFor仍然存在,仍然可以使用。

HtmlHelpers和TagHelpers之间的区别在于HtmlHelpers选择为您呈现哪些html元素,而TagHelpers使用您自己添加的html标记,以便您可以更全面地控制使用的html元素。您可以使用HtmlHelpers模板控制标记,但您可以使用TagHelper获得更多控制权。

所以你应该考虑我想要包装这个模型属性的html标记,并使用@ Model.Property在它周围添加一些标记来围绕属性本身添加标记,或者如果你愿意让它继续使用DisplayFor助手决定。

答案 1 :(得分:6)

您可以创建自己的标记助手

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>

答案 2 :(得分:1)

我一直将它用作显示标记助手。

[HtmlTargetElement("*", Attributes = ForAttributeName)]
public class DisplayForTagHelper : TagHelper
{
    private const string ForAttributeName = "asp-display-for";
    private readonly IHtmlHelper _html;

    public DisplayForTagHelper(IHtmlHelper html)
    {
        _html = html;
    }

    [HtmlAttributeName(ForAttributeName)]
    public ModelExpression Expression { get; set; }

    public IHtmlHelper Html
    {
        get
        {
            (_html as IViewContextAware)?.Contextualize(ViewContext);
            return _html;
        }
    }

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext ViewContext { 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 type = Expression.Metadata.UnderlyingOrModelType;
        if (type.IsPrimitive)
        {
            output.Content.SetContent(Expression.ModelExplorer.GetSimpleDisplayText());
        }
        // Special Case for Personal Use
        else if (typeof(Dictionary<string, string>).IsAssignableFrom(type))
        {
            output.Content.SetHtmlContent(Html?.Partial("Dictionary", Expression.ModelExplorer.Model));
        }
        else
        {
            var htmlContent = Html.GetHtmlContent(Expression);
            output.Content.SetHtmlContent(htmlContent);
        }
    }
}

public static class ModelExpressionExtensions
{
    public static IHtmlContent GetHtmlContent(this IHtmlHelper html, ModelExpression expression)
    {
        var ViewEngine = html.ViewContext.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
        var BufferScope = html.GetFieldValue<IViewBufferScope>();
        var htmlContent = new TemplateBuilder(ViewEngine, BufferScope, html.ViewContext, html.ViewContext.ViewData, expression.ModelExplorer, expression.Name, null, true, null).Build();
        return htmlContent;
    }

    public static TValue GetFieldValue<TValue>(this object instance)
    {
        var type = instance.GetType(); 
        var field = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).FirstOrDefault(e => typeof(TValue).IsAssignableFrom(e.FieldType));
        return (TValue)field?.GetValue(instance);
    }
}

答案 3 :(得分:0)

try below code

public class movie
{
    public int ID { get; set; }
    [DisplayName("Movie Title")]
    public string Title { get; set; }
}
///////////////////////////////////////////////////

@model IEnumerable<MvcMovie.Models.Movie>

<h1>Show List Movies</h1>
<label asp-for="ToList()[0].Title">< /label>
@foreach (var movie in Model)
{
    @movie.Title
}
相关问题