Reputation: 5472
I have a utility class with a method to which I'm calling and passing an object from a view. I need to call Html.DisplayFor()
from within that method or simply need a way to get the property of my model formatted by the DisplayFormat
data annotation.
[DisplayFormat(DataFormatString = "{0:MMMM d, yyyy}")]
System.DateTime ReleaseDate { get; set; }
Is there any way to achieve this outside of a view? I've tried things like passing my HtmlHelper
object to the method:
public static string GetProductSnippet(Product product, HtmlHelper<List<Product>> helper)
{
return helper.DisplayFor(p => p.ReleaseDate).ToString();
}
But this won't work, as my HtmlHelper
object will not always have the same generic type. Is there some way to get the formatted version of a property without using the HtmlHelper
class?
Upvotes: 0
Views: 353
Reputation: 12324
You can use a generic type for the method:
public static string GetProductSnippet<T>(Product product, HtmlHelper<T> helper)
{
return helper.DisplayFor(p => p.ReleaseDate).ToString();
}
var markup = GetProductSnippet<List<Product>>(product, helper);
As for getting the code without the helper, you can get the implementation of the display helper from MVC source code and adjust it to your needs
Upvotes: 1