I've got a web application project in VB.NET and am trying to add an extension method for use in in a view.
Extensions.vb
Imports System.Runtime.CompilerServices
Namespace MyApp
Public Module Extensions
<Extension()> _
Public Function GetValOrDefault(ByVal dict As Dictionary(Of String, String), ByVal key As String, ByVal defaultVal As String) As String
Dim val As String
If (dict.TryGetValue(key, val)) Then
Return val
End If
Return defaultVal
End Function
End Module
End Namespace
View.cshtml
@Code
Dim msgs As Dictionary(Of String, String) = New Dictionary(Of String, String)
msgs("Foo") = "Bar"
Dim val As String = msgs.GetValOrDefault("Foo", "Bar")
End Code
However, this doesn't work, showing the following error:
'GetValOrDefault' is not a member of 'System.Collections.Generic.Dictionary(Of String, String)'.
This is a fairly straightforward extension method, and I'm not sure why it's not being picked up. Also tried adding an even simpler extension taking just a string and returning a string, with the same problem, so it seems like the extension methods aren't being picked up.
Tried compiling, also with no luck. Note, the module is in the same project as the view, but I don't think that should make any difference (I've done this in C# projects with no problems).
Is there a step or something else I'm missing that needs to be done to get this to work?
It's an old question, but, in case others are also scratching their heads, make sure you check that the Build Action of the file containing the extension is set to Compile. After two hours of going quietly insane and wondering why the extension only worked in certain places, I realised it was set to Content. A quick change to Compile and it worked. :)
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