I implemented a Module using VB.NET in order to handle localization in an MVC .NET application.
However, when I try to call the extension method LanguageSelectorLink from my view, it`s required to provide something for the first parameter of type HtmlHelper. In all C# samples I found on the Internet, this parameter is never provided and it seems to work fine.
@App_Code.LanguageSelectorLink(Nothing, "en-CA", "[English]", "English", Nothing)
Did I miss a step? Can anybody help me?
Imports System.Threading
Namespace App_Code
Public Module SwitchLanguageHelper
<System.Runtime.CompilerServices.Extension()>
Public Function LanguageUrl(ByVal helper As HtmlHelper,
ByVal cultureName As String,
Optional ByVal languageRouteName As String = "lang",
Optional ByVal strictSelected As Boolean = False) As Language
'Set the input language to lower
cultureName = cultureName.ToLower()
'retrieve the route values from the view context
Dim routeValues = New RouteValueDictionary(helper.ViewContext.RouteData.Values)
'copy the query strings into the route values to generate the link
Dim queryString = helper.ViewContext.HttpContext.Request.QueryString
For Each key In queryString
If (Not (IsNothing(queryString(key))) And
Not (String.IsNullOrWhiteSpace(queryString(key)))) Then
If (routeValues.ContainsKey(key)) Then
routeValues(key) = queryString(key)
Else
routeValues.Add(key, queryString(key))
End If
End If
Next
Dim actionName = routeValues("action").ToString()
Dim controllerName = routeValues("controller").ToString()
'set the language into route values
routeValues(languageRouteName) = cultureName
'generate the language specify url
Dim urlHelper = New UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection)
Dim url = urlHelper.RouteUrl("Localization", routeValues)
'check whether the current thread ui culture is this language
Dim current_lang_name = Thread.CurrentThread.CurrentUICulture.Name.ToLower()
Dim isSelected As Boolean
If (strictSelected) Then
current_lang_name = cultureName
Else
current_lang_name.StartsWith(cultureName)
End If
isSelected = current_lang_name
Dim language As Language = New Language()
language.Url = url
language.ActionName = actionName
language.ControllerName = controllerName
language.RouteValues = routeValues
language.IsSelected = isSelected
Return language
End Function
<System.Runtime.CompilerServices.Extension()>
Public Function LanguageSelectorLink(ByVal helper As HtmlHelper, ByVal cultureName As String, ByVal selectedText As String, ByVal unselectedText As String, ByVal htmlAttributes As IDictionary(Of String, Object), Optional ByVal languageRouteName As String = "lang", _
Optional ByVal strictSelected As Boolean = False) As MvcHtmlString
Dim language = helper.LanguageUrl(cultureName, languageRouteName, strictSelected)
Dim link = helper.RouteLink(If(language.IsSelected, selectedText, unselectedText), "Localization", language.RouteValues, htmlAttributes)
Return link
End Function
End Module
End Namespace