开发者

Change culture in MVC

开发者 https://www.devze.com 2022-12-21 15:53 出处:网络
I\'m using URL based localization logic in my MVC app. so, default route would be mysite/someControler, and localized route would be mysite/en-US/someControler.

I'm using URL based localization logic in my MVC app. so, default route would be mysite/someControler, and localized route would be mysite/en-US/someControler.

"en-US" is value for "c开发者_如何学编程ulture" parameter which has default value.

I'm wondering what is there any generic way to switch between cultures, and keep all the url route values and parameters?

Thanks


I do something simple:
In my base controller (all other controllers inherits from it) I set the following ViewData bits:

    If Request.Path.Contains("/en/") Then
        ViewData("PathEs") = Request.Path.Replace("/en/", "/es/")
        ViewData("PathPt") = Request.Path.Replace("/en/", "/pt/")
    ElseIf Request.Path.Contains("/pt/") Then
        ViewData("PathEn") = Request.Path.Replace("/pt/", "/en/")
        ViewData("PathEs") = Request.Path.Replace("/pt/", "/es/")
    Else
        ViewData("PathEn") = Request.Path.Replace("/es/", "/en/")
        ViewData("PathPt") = Request.Path.Replace("/es/", "/pt/")
    End If

And then in the Master Page

 <div id="langbar">
    <% if not string.isnullorempty(ViewData("PathEs")) then %>
       <a href="<%= ViewData("PathEs") %>">Español</a>
    <% end  if %>
    <% if not string.isnullorempty(ViewData("PathEn")) then %>
       <a href="<%= ViewData("PathEn") %>">English</a>
    <% end  if %>
    <% if not string.isnullorempty(ViewData("PathPt")) then %>
       <a href="<%= ViewData("PathPt") %>">Portugues</a>
    <% end  if %>
</div>

Not too smart, but get the job done well if your are dealing with few langs (you sure can optimize both rutines)

0

精彩评论

暂无评论...
验证码 换一张
取 消