I have created HtmlHelper in ASP.NET MVC 4 razor view engine C#.
Can I pass view model property to my helper class?
For example, I have property
[Required]
[Display(Name = "Your Lastname")]
public string Lastname { get; set; }
Can I pass this property to my helper something like this @Html.Example(model => model.Lastname)
and then get data annotations in helper (if this field is required what is display name and etc.)?
The
[Display]
attribute enriches the metadata. So you could fetch the information from the metadata.For example if you wanted to retrieve the display name inside the helper:
and then if we assume that you have a view model:
you could use the helper in your strongly typed view:
Now let's suppose that you wrote a custom metadata attribute:
that you used to decorate your model with:
and then inside your helper you could fetch the custom attribute:
UPDATE:
It seems that you need to fetch the Required message. No idea why you need to do this in a custom helper but here's an example how you could achieve that: