question

badcat-1344 avatar image
0 Votes"
badcat-1344 asked ZhiLv-MSFT answered

Multi language support by Google Translate?

Hi,

I want to convert any text in terms of the language of browser.

I wrote code snippets shown below.

Here is the code to get browser language code like "fr", "de", "en"

 StringWithQualityHeaderValue preferredLanguage = null;
 if (Request.Headers.AllKeys.Contains("Accept-Language"))
 {
     preferredLanguage = Request.Headers["Accept-Language"]
         .Split(',')
         .Select(StringWithQualityHeaderValue.Parse)
         .OrderByDescending(s => s.Quality.GetValueOrDefault(1))
         .FirstOrDefault();
 }

Here is my translate function shown below.

 public string TranslateText(string input)
 {
 // Set the language from/to in the url (or pass it into this function)
 string url = String.Format
 ("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
 "tr", "de", Uri.EscapeUriString(input));
 HttpClient httpClient = new HttpClient();
 string result = httpClient.GetStringAsync(url).Result;
 // Get all json data
 var jsonData = new JavaScriptSerializer().Deserialize<List<dynamic>>(result);
 // Extract just the first array element (This is the only data we are interested in)
 var translationItems = jsonData[0];
 // Translation Data
 string translation = "";
 // Loop through the collection extracting the translated objects
 foreach (object item in translationItems)
 {
 // Convert the item array to IEnumerable
 IEnumerable translationLineObject = item as IEnumerable;
 // Convert the IEnumerable translationLineObject to a IEnumerator
 IEnumerator translationLineString = translationLineObject.GetEnumerator();
 // Get first object in IEnumerator
  translationLineString.MoveNext();
 // Save its value (translated text)
  translation += string.Format(" {0}", Convert.ToString(translationLineString.Current));
 }
 // Remove first blank character
 if (translation.Length > 1) { translation = translation.Substring(1); };
 // Return translation
 return translation;
 }

I want to combine all these two code snippet and call TranslateText function in any html part like TranslateText(@Model.Description)


How can I do that?

dotnet-aspnet-core-mvc
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ZhiLv-MSFT avatar image
0 Votes"
ZhiLv-MSFT answered

Hi @badcat-1344,

I want to combine all these two code snippet and call TranslateText function in any html part like TranslateText(@Model.Description)

You can create a service which contains the TranslateText method, then, injects the service in the view page and calling the TranslateText method.

Please refer the following steps:

Create a IViewTextFormat service with the following code (you can replace the TranslateText method to yours):

 public interface IViewTextFormat
 {
     string TranslateText(string input);
 }
    
 public class ViewTextFormat : IViewTextFormat
 {
     public string TranslateText(string input)
     {
         return input.ToUpper();
     }
 }

Register the IViewTextFormat service in the ConfigureServices method:

     public void ConfigureServices(IServiceCollection services)
     {
          services.AddScoped<IViewTextFormat, ViewTextFormat>();

Then, in the View page, injects the service:

 @model List<Core3_1MVC.Models.Student>
    
 @using Core3_1MVC.Services
 @inject IViewTextFormat TextFormat
 @{
     ViewData["Title"] = "Home Page";
 }
 <div class="text-center">
     <h1 class="display-4"> @TextFormat.TranslateText("Welcome")</h1>
     <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
 </div>
    
 <table class="table table-hover">
     <thead>
         <tr><td>Name</td><td>EnrollmentDate</td></tr>
     </thead>
     <tbody>
         @foreach (var item in Model)
         {
             <tr><td>@TextFormat.TranslateText(item.FirstMidName)</td><td>@item.EnrollmentDate</td></tr>
         }
     </tbody>
 </table>

The result as below:

127257-28.gif

If you want to use the service in the controller method, you can also inject the service in the controller and call the TranslateText method, refer Dependency injection in ASP.NET Core.

Besides, ASP.NET Core provides services and middleware for localizing into different languages and cultures. You can also try to use it: Globalization and localization in ASP.NET Core.


If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Best regards,
Dillion


28.gif (520.2 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.