I have resource file in English and japans, so is my website turn to japans language need to display japans messages same as English, so need to display messages dynamically in java script.
Thank you.
you can add resources.resx to your project and write the function below in a common controller.
#if !DEBUG
[OutputCache(Duration = 24 * 60 * 60)]
#endif
[AllowAnonymous]
public ActionResult ResourcesForJavascript()
{
try
{
var resourceSet = JsResources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
var resourceDictionary = resourceSet
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = JsonConvert.SerializeObject(resourceDictionary);
var javaScript = $"window.Resources = window.Resources || {{}}; window.Resources.resources = {json};";
return JavaScript(javaScript);
}
catch (Exception ex)
{
WebExceptionHelper.FillModelStateOrTempDataWithExceptionMessages(ex, ModelState, TempData);
return null;
}
}
And call it as follows in the _Layout.cshtml
<script type="text/javascript" src="@Url.Action("ResourcesForJavascript", "CommonActions")"></script>
To use resource file message, you need to inject Locatization on related view. Example: assume you have a view with the name abc.cshtml and you want to show an alert message from resource file when a button is clicked
View: abc.cshtml
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
in script section
<script type="text/javascript">
function callOnButtonClick(){
alert('@Localizer["Hello message from resource"]');
}
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.