Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use DisplayNameForModel?

I tried using this as a header for a view but it returns an empty string. In the Razor layout, I have something like:

@model IEnumerable<MVCApp.Models.Model>
<h2>@Html.DisplayNameForModel()</h2>

Do I need to set something on the model definition itself? I tried a data annotation [Display(Name="Model Name")] but it is a build error:

Attribute 'Display' is not valid on this declaration type. It is only valid on 'method, property, indexer, field, param' declarations.

The documentation DisplayNameExtensions.DisplayNameForModel Method is terse. The syntax calls for a parameter, but says:

No overload for method 'DisplayNameForModel' takes 1 arguments

As the Usage section says "When you use instance method syntax to call this method, omit the first parameter"

So, how do I use this method to return something?

like image 511
ShooShoSha Avatar asked Mar 12 '15 23:03

ShooShoSha


1 Answers

I just used the default MVC 5 template project in VS2013 and have the @Html.DisplayNameForModel() working with no issues.

First, you are using the wrong data annotation on your view model. You want to use [DisplayName("My Model Name")] and not [Display()]

[DisplayName("Test View Model")]
public class TestViewModel

{
    public string TestProperty { get; set; }
}

Second, the html parameter you are seeing on MSDN is a required parameter for any Html helpers in MVC. You do not have to pass anything for this value, the view engine does this for you. So, in your view, you would use the following to get the Display Name that you set on the model as so.

<h2>@Html.DisplayNameForModel()</h2>

Now, your result should output the display name attribute you set in your html. *Note the Test View Model above the Log In text.

enter image description here

like image 50
Tommy Avatar answered Oct 02 '22 18:10

Tommy