I have created a SumFor
extension method on HtmlHelper. The purpose is to take a property from a model and calculate the sum of all values and return it. This works, but the value is returned as a plain string. Eg:
130.50
I often use custom attributes on my properties such as
<Percentage>
Public Property Amount As Decimal
And
<Currency>
Public Property Amount As Decimal
Which use DisplayTemplates Percentage.vbhtml and Currency.vbhtml in ~/Views/Shared/DisplayTemplates.
These render strings like:
80%
$130.50
(Although a little more complex)
This is my currency approach:
<Extension>
Public Function SumFor(Of TModel As IEnumerable(Of Object),
TProperty As ModelMetadata) _
(helper As HtmlHelper(Of TModel),
expression As Expression(Of Func(Of TModel, TProperty))) _
As IHtmlString
Dim data As ModelMetadata
Dim viewName As String = String.Empty
Dim sum As String
data = expression.Compile.Invoke(Nothing)
sum = data.GetSum(helper.ViewData.Model)
If data.DataTypeName IsNot Nothing Then viewName = data.DataTypeName
If data.TemplateHint IsNot Nothing Then viewName = data.TemplateHint
Return helper.Partial(viewName, sum)
End Function
As you can see I'm trying to use the helper's Partial method to ensure that the correct display template is used. But I get an error saying that the view cannot be found. I want to have my sum value used like a normal DisplayFor
so that a display template is chosen, but I don't know how to use the HtmlHelper with my sum string.
I feel like I'm going about this the wrong way. What's the best solution here?