可以在GET视图中使用DataAnnotation.UIHInt

时间:2018-02-02 02:40:08

标签: asp.net-core-mvc asp.net-core-2.0

可以在System.ComponentModel.DataAnnotations.UIHInt视图中使用GET

application.json中指定:

{
  "ApplicationSettings": {
    "ApplicationName":  "My Application"
  }
  ...
}

ApplicationSettings上课:

public class ApplicationSettings
{
    [UIHint("The name of the application displayed in nav bar")]
    public string ApplicationName { get; set; }
}

填充在Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  // retrieve the 'ApplicationSettings' section of the appsettings.json file
  var applicationSettings = Configuration.GetSection("ApplicationSettings");
  services.Configure<ApplicationSettings>(applicationSettings);
  ...
}

(以某种方式)添加到/Home/About

<h3>ApplicationSettings</h3>
<div>
    <dl class="dl-horizontal">
        <dt>ApplicationName</dt>: <dd>@ApplicationSettings.Value.ApplicationName</dd>
    <????>
...
</div>

以HTML格式显示:

ApplicationSettings

ApplicationName: My Application
The name of the application displayed in nav bar

1 个答案:

答案 0 :(得分:1)

嗯,首先,您使用的是UIHint错误。它旨在指定DisplayFor / EditorFor将使用的视图。因此,在这方面,是的,您也可以通过DisplayFor将其用于展示。

但是,你在这里做的只是描述这个属性的用途。这是Display属性的工作:

[Display(Name = "The name of the application displayed in nav bar")]

然后,您可以这样做:

@Html.DisplayNameFor(x => ApplicationSettings.Value.ApplicationName)

但是,即使这不是技术上你想要的。更可能的是,您仍然希望显示名称类似于Application Name,除此之外,这应该是真正的描述性文本。 Display属性 具有Description属性,您可以使用该属性:

[Display(Name = "Application Name", Description = "The name of the application displayed in nav bar")]

然而,遗憾的是,没有内置的实际显示Description的方法。 another SO answer包含您可以添加的扩展程序。

public static class HtmlExtensions
{
    public static IHtmlContent DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
    {
        if (html == null)
            throw new ArgumentNullException(nameof(html));
        if (expression == null)
            throw new ArgumentNullException(nameof(expression));

        var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, html.ViewData, html.MetadataProvider);
        if (modelExplorer == null)
            throw new InvalidOperationException($"Failed to get model explorer for {ExpressionHelper.GetExpressionText(expression)}");

        return new HtmlString(modelExplorer.Metadata.Description);
    }
}
     

礼貌:Wouter Huysentruit

相关问题