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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With