0

Can System.ComponentModel.DataAnnotations.UIHInt be used in a GET view:

Specified in application.json:

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

ApplicationSettings class:

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

Populated in 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);
  ...
}

Added (somehow) to /Home/About:

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

Displayed in HTML:

ApplicationSettings

ApplicationName: My Application
The name of the application displayed in nav bar
craig
  • 25,664
  • 27
  • 119
  • 205

1 Answers1

2

Well, first, you're using UIHint wrong. It's intended for specifying a view that will be used by DisplayFor/EditorFor. So, in that respect, yes you can use it for display, as well, via DisplayFor.

However, what you're doing here is just describing what this property is for. That's a job for the Display attribute:

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

Then, you can just do:

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

However, even this isn't technically what you want. More likely than not, you still want the display name to be something like Application Name, and this should truly be descriptive text in addition to that. The Display attribute does have a Description property you can use for that:

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

However, there's no built-in way to actually display that Description, unfortunately. There's another SO answer that contains an extension you can add for that though.

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);
    }
}

Courtesy: Wouter Huysentruit

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444