eWorld.UI - Matt Hawley

Ramblings of Matt

ASP.NET MVC: Simplified Localization via ViewEngines

October 22, 2008 16:56 by matthaw

Thanks to Brad, he identified a few areas that made things MUCH simpler from my prior implementation. Notably, while you still have your ViewEngine specify "here's your view's path" there's no longer a need for having a new helper, derived classes, etc. This implementation goes back to the simplified HtmlHelper extension in which you can use in any ViewEngine regardless. It also allows you to "replace" the implementation by just changing the namespace, just as you can do with Html and Ajax.

 

Simplified View Engine

As previously stated, you still need a new view engine and view, because this is the only point in which you can truly grab which view is being rendered. What's nice now, is that it has been simplified down to using the base implementation and only setting a ViewData field in which the Resource extension method picks up and uses.

   1:  public class LocalizationWebFormViewEngine : WebFormViewEngine
   2:  {
   3:      protected override IView CreateView(ControllerContext controllerContext, 
   4:                                                  string viewPath, string masterPath)
   5:      {
   6:          return new LocalizationWebFormView(viewPath, masterPath);
   7:      }
   8:   
   9:      protected override IView CreatePartialView(ControllerContext controllerContext, 
  10:                                                                            string partialPath)
  11:      {
  12:          return new LocalizationWebFormView(partialPath, null);
  13:      }
  14:  }
  15:   
  16:  public class LocalizationWebFormView : WebFormView
  17:  {
  18:      internal const string ViewPathKey = "__ViewPath__";
  19:   
  20:      public LocalizationWebFormView(string viewPath) : base(viewPath)
  21:      {
  22:      }
  23:   
  24:      public LocalizationWebFormView(string viewPath, string masterPath) 
  25:                : base(viewPath, masterPath)
  26:      {
  27:      }
  28:   
  29:      public override void Render(ViewContext viewContext, TextWriter writer)
  30:      {
  31:          // there seems to be a bug with RenderPartial tainting the page's view data
  32:          // so we should capture the current view path, and revert back after rendering
  33:          string originalViewPath = (string) viewContext.ViewData[ViewPathKey];
  34:          
  35:          viewContext.ViewData[ViewPathKey] = ViewPath;
  36:          base.Render(viewContext, writer);
  37:          
  38:          viewContext.ViewData[ViewPathKey] = originalViewPath;
  39:      }
  40:  }

As you can see, it's much simpler now. Also, it seems as if there's a bug with the current Beta bits when you have a RenderPartial on your page, there's no isolation and the view's path is not correct later. Simple fix by simply grabbing the original view path, setting it to the new path, rendering, and then reverting back.

 

Getting back to Extension Methods

And now that we have our path again in our ViewData, we can revert back to using extension methods to extract the path when doing both Global and Local resources. As you can see below, should you be using any other ViewEngine it will always work for Global resources.

   1:  public static class ResourceExtensions
   2:  {
   3:      public static string Resource(this Controller controller, string expression, 
   4:                                                    params object[] args)
   5:      {
   6:          ResourceExpressionFields fields = GetResourceFields(expression, "~/");
   7:          return GetGlobalResource(fields, args);
   8:      }
   9:   
  10:      public static string Resource(this HtmlHelper htmlHelper, 
  11:                                                    string expression, params object[] args)
  12:      {
  13:          string path = (string)htmlHelper.ViewData[LocalizationWebFormView.ViewPathKey];
  14:          if (string.IsNullOrEmpty(path))
  15:              path = "~/";
  16:   
  17:          ResourceExpressionFields fields = GetResourceFields(expression, path);
  18:          if (!string.IsNullOrEmpty(fields.ClassKey))
  19:              return GetGlobalResource(fields, args);
  20:   
  21:          return GetLocalResource(path, fields, args);
  22:      }
  23:   
  24:      static string GetLocalResource(string path, ResourceExpressionFields fields, 
  25:                                                       object[] args)
  26:      {
  27:          return string.Format((string)HttpContext.GetLocalResourceObject(path, 
  28:                                 fields.ResourceKey, CultureInfo.CurrentUICulture), args);
  29:      }
  30:   
  31:      static string GetGlobalResource(ResourceExpressionFields fields, object[] args)
  32:      {
  33:          return string.Format((string)HttpContext.GetGlobalResourceObject(
  34:               fields.ClassKey, fields.ResourceKey, CultureInfo.CurrentUICulture), args);
  35:      }
  36:   
  37:      static ResourceExpressionFields GetResourceFields(string expression, 
  38:                                                                string virtualPath)
  39:      {
  40:          var context = new ExpressionBuilderContext(virtualPath);
  41:          var builder = new ResourceExpressionBuilder();
  42:          return (ResourceExpressionFields)builder.ParseExpression(
  43:                                            expression, typeof(string), context);
  44:      }
  45:  }

Again, thanks to Brad, this implementation seems "less dirty". You can download the source for this here.

 

kick it on DotNetKicks.com

Comments

October 25. 2008 20:06

Hi, matthaw.
Very cool solution Smile I like it.
I think you should contribute it to MvcContrib project. It doesn't have such useful functionality at the moment.
Thank you

zihotki

October 26. 2008 05:05

Indeed it is a really cool solution.
This is actually what i was looking for to localize/globalize a site which uses ASP.NET MVC.
So i am grateful to you for showing me the way.

Tasarım

October 30. 2008 00:45

I think your posts lacks a lot of details. How do I register the view engine as default for one? Called the ViewEngines.Add() in my Global.asax, but it does hit it. Thus I cant use local resources.

Please provide rich examples on how to use the code.

Hans G

November 18. 2008 07:44

Hello,

Can you provide an example on how to use this code?

Thanks in advance.

Rafael Pol

November 22. 2008 03:47

Hi Matt,
I could register the ViewEngine with Beta1 but still didnt manage to use local resources.
Could you please post a web that uses the Viewengine?
Thnx
Mathias

Mathias Fritsch

November 25. 2008 03:54

hmn, could u post a example plz

zeroonea

December 24. 2008 19:52

Hello, I need some example codes, thanks

C.T.

December 31. 2008 10:12

anyone can post an example code about how to use this in the controller?
thanks

C.T.

December 31. 2008 12:30

I have know how to use this code, but I cannot know how to use local resources in the controllers.

C.T.

January 5. 2009 01:03

Good solution for MVC localization.
But i dont know how to register "LocalizationWebFormViewEngine" as :
"ViewEngines.Engines.Add(new LocalizationWebFormViewEngine());"
in "Application_Start" does not work for LocalResource files.

Thnx for some example.

Feryt

January 5. 2009 01:15

I have finally found solution :

      ViewEngines.Engines.Clear();
      ViewEngines.Engines.Add(LocalizationWebFormViewEngine());
Hope it helps.

Feryt

January 11. 2009 17:08

I can't seem to make it work. I registered the viewengine and that's good. But when I am trying to retrieve a resource from the global resource file, I keep getting "The resource object with key 'myTestKey' was not found."

Can anyone post a complete example on how to position correctly resource files and how to call methods? Thanks

Sgro

January 12. 2009 16:01

@Sgro
Global resources files must be located in special Asp.Net folder called "App_GlobalResources"  in Web Root(right click on web project "Add/Add ASP.NET Folder/App_GlobalResources").
Hope it helps.

Feryt

January 21. 2009 13:42

Good Article,but i cant understand the localisation in mvc. Please explain with good example.

bhupendran

January 21. 2009 14:13

@bhupendran:
It doesn't matter if you localize in MVC or WebForms(except asp:localize server control, of course). The rule is the same.
Matthaw, has written nice extension function(for HtmlHelper and Control classes) it this blog, you just use it :
- in view "~/Views/Home/Index.aspx" : <%=Html.Resource("KeyInResourceFile") %> (note: in "~/Views/Home/" must be "App_LocalResources" directory with localized resource files "Index.aspx.resx"(default language) and "Index.aspx.XX.resx"(where XX is LanguageCode))
For Global resource : <%=Html.Resource("Strings, KeyInFlobalResourceFile") %> in site root is "App_GlobalResources" dir with "Strings.resx" file.

Hope it helps.
F.

Feryt

January 21. 2009 15:05

@bhupendran:
Hi there,
global resources stands for resources, which are not part of a certain page(view).
For example, if you need localized menu on each page(and dont want to use master page) you just put localized resources to build this menu in Global resource file(let it be "Strings.resx") and on every view just call Html.Resource("Strings, MenuKey") to get localized menu data(ie xml).
The format of Resource() function parrameter is "<GlobalResourceFileNameWithOutExtension>, <Key>" so, if you provide <GlobalResourceFileNameWithOutExtension> the function looks in this file in "App_GlobalResources" dir, else it looks for local resource in current view context.

Best regards. F.

Feryt

January 21. 2009 15:38

Hi Feryt,

This below function is given by you.

public static string Resource(this Controller controller, string expression,params object[] args)
             {
                 ResourceExpressionFields fields = GetResourceFields(expression, "~/");
                 return GetGlobalResource(fields, args);
             }

In   this Resource fucntion you are passing 3 arguments. what this argument is for,like
this Controller controller=?;string expression=?,params object[] args=?;
  
This is my code "<%=Html.Resource("Username")%>" what are the 2 arguments i have to pass and how should i have to call that class . please tell me the whole procedure with example.

Thanks
bhupendran.m

bhupendran

January 21. 2009 15:44

Hi Feryt,

Thanks for ur reply .I have already implemented your opinion in my project.But my big doubt is where should i use this global resource code like you mentioned " <%=Html.Resource("Strings, KeyInFlobalResourceFile") %> " and what is the purpose of this code. Please explain me this .Its very urgent.

Once again thanks
bhupendran.m

bhupendran

January 21. 2009 15:54

@bhupendran
Hi bhupendran.
Well "public static <returnType> <FuncName>(this <ObjectToExtend> o, ...)" is a C# pattern for extension methods Check it here : msdn.microsoft.com/en-us/library/bb383977.aspx .

So, "public static string Resource(this Controller controller, string expression,params object[] args) " extends Controller object.
If you add reference in your project to Assembly containing "ResourceExtensions" class and declare "using" it's namespace, now all of Controller objects will provide "Resource(string expression,params object[] args)" function. So you dont ever need to specify "this Controller controller" param. -> i.e. in Index action of HomeController, you can call "Resource("Strings, Key") for Global resource or Resource("key") for local resource.

If you have any futher questions, i'll try to help you.
Have a nice day.

Feryt

January 21. 2009 16:13

Hi Feryt,

i m really sorry to disturb u again and again but i m really in a situation that i need ur full support. Please help me out.

I will tell u the step i have done for localisation in mvc in my project.Please tell me whether i am in the correct path or not.
1.I have created a class files named "ResourceExtensions","LocalizationWebFormViewEngine ","LocalizationWebFormView ".

2.I have create a global resource file and put the "Strings.resx" file inside the global resource folder.

3. I have create 2 local resx file inside the home folder "Index.aspx.resx"(default language) and "Index.aspx.XX.resx". as u mentioned above.

Now please tell me which assembly name i have to get and implement.

Thanks
bhupendran.m

bhupendran

January 21. 2009 16:15

Thanks Feryt,

i m really sorry to disturb u again and again but i m really in a situation that i need ur full support. Please help me out.

I will tell u the step i have done for localisation in mvc in my project.Please tell me whether i am in the correct path or not.
1.I have created a class files named "ResourceExtensions","LocalizationWebFormViewEngine ","LocalizationWebFormView ".

2.I have create a global resource file and put the "Strings.resx" file inside the global resource folder.

3. I have create 2 local resx file inside the home folder "Index.aspx.resx"(default language) and "Index.aspx.XX.resx". as u mentioned above.

Now please tell me which  assembly name i have to get and implement.

Thanks
bhupendran.m

bhupendran

January 21. 2009 16:18

Thanks Feryt,

I will try this out.Thanks you very much. If i have any doubt in mvc i will ask u.

thanks
bhupendran.m

bhupendran

January 21. 2009 16:18

Hi there.
I put a project together, you can download it here : http://code.google.com/p/aspmvclocalization/
Main things:
1)check "Global.asax" "Application_Start()"
2)check "~/App_GlobalResources","~/Views/Home/App_LocalResources, "~/Views/Home/Index.aspx" and "HomeController.cs"

F.

Feryt

January 21. 2009 16:36

Thanks Feryt,

     I will try this out.Thanks you very much. If i have any doubt in mvc i will ask u.

thanks
bhupendran.m

bhupendran

January 21. 2009 16:41

Hi Feryt,

         Thanks for ur reply .I have already implemented your opinion in my project.But my big doubt is where should i use this global resource code like you mentioned " <%=Html.Resource("Strings, KeyInFlobalResourceFile") %> "  and what is the purpose of this code. Please explain me this .Its very urgent.

Once again thanks
bhupendran.m

bhupendran

January 21. 2009 16:57

Hi feryt,

  Thanks for ur code .It really works fine. But when i add another Local resource file like "Index.aspx.fr.resx" and give some key "Mykey "and values " " in that "Index.aspx.fr.resx"  file . My code is getting an error that "The resource object with key 'Mykey' was not found."

Please give me the solution where  i have to change my code if i add another local resouce file .How can i tell my project that i need the whole project in french or spanish any language. Please give me a simple example.

Thanks
bhupendran.m

bhupendran

January 21. 2009 17:11

@bhupendran
HI bhupendran, i'm happy that my demo project helps you.
When accessing resource files, .NET Framework choose wchich localized resource to use by checking :  "Thread.CurrentThread.CurrentUICulture".
The best way is to change "Thread.CurrentThread.CurrentCulture" too. In my MVC project i have base class for all of my Controllers and overriding Execute method :
public abstract class LocalizedControllerBase : ControllerBase
{
    protected override void Execute(System.Web.Routing.RequestContext requestContext)
    {
      string languageCode = requestContext.RouteData.Values["languageCode"].ToString();

      if ( !AppConfig.SupportedLanguageCodes.Contains(languageCode) )
        languageCode = AppConfig.DefaultLanguageCode;

      System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture(languageCode);
      Thread.CurrentThread.CurrentCulture = culture;
      Thread.CurrentThread.CurrentUICulture = culture;

      base.Execute(requestContext);
    }
}


Note, in this scenario, you must have routes setting, that allways gives to controller "languageCode" key in "RouteData.Values" collection.
My URL looks like "localhost/{languageCode}/{controller}/{action}"

Have you placed "Mykey" in default language resource file too? IMHO you get error becouse "Thread.CurrentThread.CurrentUICulture" is set to English. Try this(before calling Resource() extension method) "Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.CreateSpecificCulture("fr")"

Let me know if it helps you. Or contact me on email(skorunka@seznam.cz) or ICQ:53680863

Bye.

Feryt

January 21. 2009 17:14

One point:

if ( !AppConfig.SupportedLanguageCodes.Contains(languageCode) )
   languageCode = AppConfig.DefaultLanguageCode;

is not necessary, it just check if language from URL is supported, if not defaults it to "en"...

Feryt

January 22. 2009 01:17

Good Morning feryt,

Thanks for your reply. but i have doubt about how to implement ur abstract class "LocalizedControllerBase " . And how can i use ur base class in controller .Please send the full flegde example for " localisation in mvc" which can handles others languages too.

Thanks
bhupendran.m

bhupendran

January 22. 2009 02:10

Hi feryt ,

        I have one more doubt how can we set  routes for "language code".Please send me the full project.

Thanks
bhupendran.m

bhupendran

January 22. 2009 05:09

@bhupendran
Good day bhupendran,
i have updated project ro teflect your requests.
You can read about routing here : weblogs.asp.net/.../...ork-part-2-url-routing.aspx

Feryt

January 22. 2009 05:21

@bhupendran
Answers on both Q is NO.
If you want to use server controls and postbacks(code-behind files and so on) you shoud stay with webforms.
You can read about MVC pattern nice post here : weblogs.asp.net/.../asp-net-mvc-framework.aspx.
MVC pattern and WebForms are two different words, each have its advantages and disadvatages.

Feryt

January 22. 2009 05:36

Hi feryt,

Thanks it works fine .But when i go to next page like "aboutUS.aspx"  its give an error "'System.Web.Mvc.HtmlHelper' does not contain a definition for 'Resource' and no extension method 'Resource' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)".Please give me the solution.

Thanks
bhupendran.m

bhupendran

January 22. 2009 05:51

Thanks Feryt,

Your project work fine.I wil be in touch with you always.

Regards
bhupendran.m


bhupendran

January 22. 2009 05:52

Hi feryt,

As per ur suggestion u told me we cant do postback in dropdown.

If i have many languages links in a particular page like french,enlish,spanish etc and if u want ur page should be full of spanish then u have to click the link called spanish. but my doubt is that how can u pass this "spanish" value to global.asax  so that my whole page will be converted to spanish.

If u have any other options for that u can tell me i will implement in my project.

Thanks
bhupendran.m

bhupendran

January 22. 2009 05:59

i will implement ur code in my project and let u know.

thanks again
bhupendran.m

bhupendran

January 22. 2009 06:04

@bhupendran
You shoud build languages links with HtmlBuilder. Each View has its own HtmlBuilder instance :
<%=Html.GenerateLink("language name", "RouteName", "Controller.Action", "Cotroller", new RouteValueDictionary(new {languageCode = "en"}), null) %>

In my demo project it goes like this:
<%=Html.GenerateLink("French", "DefaultWithLanguage", "Index", "Home", new RouteValueDictionary(new {languageCode = "fr"}), null) %>
it generates something like this :
  <a href="localhost/fr/home/index">French</a>
F.

Feryt

January 22. 2009 06:05

@bhupendran
No problem, you are welcome.
Bye.
F.

Feryt

January 22. 2009 06:10

I have a new post on my blog, about my simple Asp.Net MVC localization project :
http://feryt.spaces.live.com/blog/cns!2A7829BEF8D0664B!162.entry

Feryt

January 22. 2009 06:16

Hi feryt,

I have a 2 doubts.
1.can we use server controls(webform) in our mvc project.
2.can we do postback in dropdownlist(html control) in mvc project.

Thanks
bhupendran.m

bhupendran

January 22. 2009 09:11

Hi feryt,

         I have implement ur code in my web.congif file now its work fine for global resources.but  for  local resource like "Index.aspx.fr.resx" and "Index.aspx.resx"  i gave the same "Name=LOCALKEY" in both the resource file . but when i go to "About us page" its shows  me an error "The resource object with key 'LocalKey' was not found.". Please give me the solution.

Thanks
bhupendran.m

bhupendran

January 22. 2009 09:30

Hi feryt,

I have implement ur code in my web.congif file now its work fine for global resources.but for local resource like "Index.aspx.fr.resx" and "Index.aspx.resx" i gave the same "Name=LOCALKEY" in both the resource file . but when i go to "About us page" its shows me an error "The resource object with key 'LocalKey' was not found.". Please give me the solution.

here is my code for Index.aspx

Global resource : <%=Html.Resource("Strings, GlobalResourceKey") %><br />
Local resource  : <%=Html.Resource("LocalKey")%><br />

here is my code for AboutUS.aspx

Global resource : <%=Html.Resource("Strings, GlobalResourceKey") %><br />
Local resource  : <%=Html.Resource("LocalKey")%><br />

both r same but i dont know why its show error "The resource object with key 'LocalKey' was not found" when i go to aboutUs page for local resource


Thanks
bhupendran.m

bhupendran

January 23. 2009 02:56

Goodmorning feryt,

My project is working fine.I have a new secenario like if in my first page i have select the spanish language it will go to login page .After entering the username and password if u press submit button the page will be redirected to the home page but in that page i m not getting the globalisation.I think i have some problem with my submit button.  I want to know that what r the parameter's i have to pass from my submit button so that i can get the same language in the other page.Please explain with some example .

Please do the needful.

Thanks
bhupendran.m

bhupendran

January 23. 2009 03:00

hi,

I have two .resx file in globalization folder (English,French). I selected an language in that page which changes to specified language, I have an action method in controller which redirects to next page when an action occurs in the aspx page. How to pass the selected langauage .resx file to next page in the controller action method

thanks
senthil

senthil

January 23. 2009 03:14

Hi, you can set selected language in few ways :
1)in cookie on client side
2)in session on server side
3)or everywhere use urls like this "en/home/index", so you can parse language from URL

F.

Feryt

January 23. 2009 03:26

hi Feryt,

Thanks for your reply, i we can do like this  "en/home/index". But my point is , for example in login form i have the language selection option. If i select french language and my page label text will change to french after i submitting userid ,password and clicked the button . I gives error like this.

The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

I have the following code in controller

[AcceptVerbs("GET")]
    public ActionResult Index()
    {
      //fron Controller we can only acces global resources, since we dont have a path to a View...
      ViewData["Message"] = "From Controller -> " + this.Resource("Strings, GlobalResourceKey");

      return View();
    }

        [AcceptVerbs("POST")]
        public ActionResult Index(FormCollection form)
        {
            //ViewData["Message"] = "Go to About.aspx";
            return RedirectToAction("About", "Home", RouteData.Values["languageCode"]);
        }


        [AcceptVerbs("GET")]
    public ActionResult About()
    {
            //ViewData["Title"] = "About Page";
            ViewData["Message"] = "From Controller -> " + this.Resource("Strings, GlobalResourceKey");

      return View();
    }


And i have following code in Index.aspx

<form id="form1" method="post" action="/Home/Index" >
    Global resource : <%=Html.Resource("Strings, GlobalResourceKey") %><br />
    <%= Html.Encode(ViewData["Message"])%>
    <%--Local resource : <%=Html.Resource("LocalKey")%><br />--%>
    <a href="/Home/About">about</a>
    <input type="submit" value="submit" />
  </form>



senthil

January 23. 2009 03:48

hi feryt,

kindly provide solution to me.

thanks
senthil

senthil

January 23. 2009 04:22

HI Senthill,
u get eroro on this lien : <%--Local resource : <%=Html.Resource("LocalKey")%><br />--%>  ?
If you do, fist chek for "Index.aspx.resx"(or "Index.aspx.fr.resx"...) in "App_LocalResources" folder. "App_LocalResources" folder must be located in the same directory as "Index.aspx" view. Then check if you use valid keys(kye must be in every localized file("Index.aspx.resx", "Index.aspx.fr.resx" ...). Kyes are case-sensitive.

F.

Feryt

January 23. 2009 04:37

hi feryt,

your reply work me well. I have a new scenerio in this i am using only globalization files no Localiation  (App_GlobalResources folder only). I have two global resources files (french,english ie two files). I have two aspx files in Views (Index,About). By default i make english  global resources file to access in my aspx files .
In my Index page i changed from english to french  global resources file. I have a button which makes a call to controller to Redirect to About.aspx page with the selected global resources file. But its not changing, it gives error that resource is not found. Indicating it also needs to send the language along with the url .how to send selected langauge to the controller

In global resource file i have Strings.resx,Strings.fr.resx respectively in AppGlobalResource folder. I am giving the following code to you.

Index.aspx page

french:<%=Html.GenerateUrl(.........)%>  ( to move from one global resource to another)
english:<%=Html.GenerateUrl(........)%>

<form id="form1" method="post" action="/Home/Index" >
Global resource : <%=Html.Resource("Strings, GlobalResourceKey") %>
<%= Html.Encode(ViewData["Message"])%>


<input type="submit" value="submit" />
</form>

Home Controller:

[AcceptVerbs("GET")]
public ActionResult Index()
{
//fron Controller we can only acces global resources, since we dont have a path to a View...
ViewData["Message"] = "From Controller -> " + this.Resource("Strings, GlobalResourceKey");

return View();
}

[AcceptVerbs("POST")]
public ActionResult Index(FormCollection form)
{
//ViewData["Message"] = "Go to About.aspx";
return RedirectToAction("About", "Home", RouteData.Values["languageCode"]);
}


[AcceptVerbs("GET")]
public ActionResult About()
{
//ViewData["Title"] = "About Page";
ViewData["Message"] = "From Controller -> " + this.Resource("Strings, GlobalResourceKey");

return View();
}


About.aspx

<form id="form1"  >
Global resource : <%=Html.Resource("Strings, GlobalResourceKey") %><br />
<%= Html.Encode(ViewData["Message"])%>
<a href="/Home/About">about</a>
<input type="submit" value="submit" />
</form>


If i select french in index.aspx page and then my two aspx file should be french.otherwise if i select english i should to english.

waiting for you response

thank's in advance

senthil


senthil kumar

January 23. 2009 06:25

Hi,
hmm, try to watch, what is "Thread.CurrentThread.CurrentUICulture" equals to.
Comment line which trows error and put this instead :
<%=Thread.CurrentThread.CurrentUICulture %>

Now you can see if language is sets propperly.
Let me know...
F.

Feryt

January 23. 2009 17:13


Hi feryt,

How r u doing. Senthil is my friend. We both r working on the same project.

Ryt now i m working on this :

1.How to use exception handling in mvc using Microsoft Exception Management Application Block. Plaese give me some examples on this.

2. How to use ajax in mvc.

3.How to make autopost back on dropdownlist(html control).

Please do the needful.

Thanks
bhupendran.m

bhupendran

January 23. 2009 21:29

Hi feryt,

How to handle the error in Microsoft Exception Management Application Block when an error occurs in the global application.Give me an sample

regards,
senthil

senthil kumar

January 23. 2009 23:03

hi freyt,

I try well but it not works. pls sent an example how to do.

thanks

regards,
senthi

senthil

January 23. 2009 23:36

Hi, i dont use "Microsoft Exception Management Application Block". I have my own logger.
F.

Feryt

January 23. 2009 23:42

hi friend,

thanks for your valueable reply, i am new to mvc pls give an example how to do with coding. I hope you will help me .

waiting for your reply,

regards,
senthil

senthil

January 24. 2009 00:19

hi,

thanks for your reply, I am showing globalization in dropdownlist. when i select an globalzation file in dropdownlist it should postback and change to the specified globalization.

help me how to do..

waiting for your valuable response

regards,
senthil

senthil

January 24. 2009 00:28

hi senthill,
use submit() function of form element in onchange event of select:
<select onchange="document.getElementById('theForm').submit()">...
In the controller action set the selected language.
F.

Feryt

January 28. 2009 15:47

hi feryt,

kindly help me how to give globalization in html.actionlink. for example i have

<%=Html.ActionLink("string name in english","ChildNew","PersonDetails") %>

how to change the "string name in english" to  "string name in french" using globalization.

thanks in advance

regards,
senthil

senthil kumar

January 28. 2009 16:05

hi Senthil, try this :
<%=Html.ActionLink(Html.Resource("KEY"),"ChildNew","PersonDetails") %>

Feryt

January 28. 2009 16:19

hi dear friends,

I thanks a lot for your reply. I have another sceniro in which i have a dropdownlist showing list of values from database. Depending on globalization i have to change the language in the droplist. I hope you will help me.

Thanks in advance

waiting for your reply

regards,
senthil

senthil kumar

January 28. 2009 16:32

hi feryt,

kindly sent how to change the dropdownlist items depending on globalization. I am still waiting for your reply

thanks

regards,
senthil kumar

senthil kumar

January 28. 2009 18:07

hi freyt,

I have a problem in binding the items to the dropdownlist depending on language selection. for example if i select french then the dropdownlist items should be in french language. if i  select english then the dropdownlist items should be english. Looking for an positive reply from you in the earliest.

regards,
shyam

shyamroy

January 29. 2009 12:51

hi freyt,

kindly give me an example how to show dropdownlist items using globalization. for example if i select spanish then my dropdownlist items should be spanish if i select englist then i should in english.

waiting for your reply

regards,
senthil

senthil kumar

February 5. 2009 05:56

Hi Freyt,

I was reading the comments and was very impressed with you patient replies to repeated queries on MVC. Keep up the good work and i hope others appreciate and spread your good work.

-Raul

Raul

February 13. 2009 13:34

Great article and works very well in conjuction to Feryt code.

Feryt, could you provide an implementation of Html.GenerateLink helper?

thanks a lot

dkarantonis

February 13. 2009 16:08


Hi shyam and shenthil,

try this:
On the Controller Action (or on the overriden base controller class), write the code below:

            Dictionary<string, string> languages = new Dictionary<string, string>();
            languages.Add("en", this.Resource("Strings, EnglishLang"));
            languages.Add("fr", this.Resource("Strings, FrenchLang"));

            ViewData["Languages"] = new SelectList(languages.Values, languages[LanguageCode]);

I am using a dictionary here for simplicity, but your languages could come from any source (database, enumeration, xml, etc...).  Also, you should add the EnglishLang and FrenchLang to your Global resources (Strings.resx ans Strings.fr.resx). The LanguageCode contains the language retrieved from the url.

Finally, add the following line the View (or Site.Master):
            <%= Html.DropDownList("Languages") %>

This way, the languages drop down list will be interpreted to the selected language and the value selected will be the corresponding one.

hope this helps,
Dimitris

dkarantonis

March 21. 2009 12:08

Ok last post on localization in MVC. Read all 3 posts and enjoyed. Thanks for this simple solution.

Bayram Çelik

July 27. 2009 17:59

Hi,
   I have been working in MVC for nearly one month. I have doubts on regarding, when dropdown item is changed how to set visible true, false for a fieldset, how to handle it in Controller, and how MVC is handled event hadlings,and  i have seen that there is no evets in MVC.. Please help me.

Thanks
Arun

ArunPrasath

August 19. 2009 05:48

I've implemented this in my current project and it seemed to be working fine until I decided to actually translate my project to a second language. For some reasons my local resources always returns the default language (from MyView.aspx.resx instead of MyView.aspx.sv-SE.resx). However, my global resources seems to be working fine. I've checked the CultureInfo.CurrentCulture and CultureInfo.CurrentUICulture properties and they hold the correct values. Anyone has any idea on why?

/ Karl

Karl

October 14. 2009 13:33

Pingback from palmmedia.de

www.palmmedia.de

palmmedia.de

November 4. 2009 18:35

Pingback from code-inside.de

HowTo: Globalization/Localization mit ASP.NET MVC | Code-Inside Blog

code-inside.de

January 9. 2010 15:06

Pingback from ducdigital.com

Noob guide to Globalization in Asp.net MVC « DucDigital

ducdigital.com

May 20. 2010 14:33

Pingback from 68.rkwrh.com

280sel Used 1969 1971 Mercedes Benz Slk32 Amg, 280sel Bulb Auto Parts

68.rkwrh.com

January 13. 2014 09:48

Pingback from ajdotnet.wordpress.com

ASP.NET MVC I18n – Part 6: Using .NET Resources | AJ's blog

ajdotnet.wordpress.com

July 9. 2015 05:51

Pingback from dexpage.com

How to localize MVC with database backed resources - DexPage

dexpage.com

July 16. 2016 06:11

Pingback from sokrachance.xyz

How To Use Getglobalresourceobject In Mvc | Embedded Commands

sokrachance.xyz

Comments are closed

Copyright © 2000 - 2024 , Excentrics World