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?
