- 新增專案類型:ASP.NET Core Web應用程式
- 目標Framework為.NET 7.0
- 在Program.cs裡的內加進如下:
var supportedCultures = new List<CultureInfo>()
{
CultureInfo.GetCultureInfo("en"),
CultureInfo.GetCultureInfo("zh")
};
app.UseRequestLocalization(new RequestLocalizationOptions()
{
DefaultRequestCulture = new RequestCulture("zh"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures,
});
其中DefaultRequestCulture = new RequestCulture("zh")為預設中文
4.在專案下新增資料夾Resources並新增SharedResources.cs,SharedResources.en和SharedResources.zh的resx資源檔
SharedResources.cs
namespace Localization
{
public class SharedResources
{
}
}
5.編輯resx的中英文如下:
6.在 _Layout.cshtm 新增如下:
<!-- 自己弄的選取語言下拉選單 -->
<select id="selectLang">
<option value="zh">中文</option>
<option value="en">English</option>
</select>
$(function () {
dropdownListSetLanguage();
$("#selectLang").on("change", function () {
changeLanguage();
});
})
/** 下拉選單選取的語系 */
function dropdownListSetLanguage() {
const urlParams = new URLSearchParams(window.location.search);
var param = urlParams.get('culture')
if (param !== null) {
$("#selectLang").val(param)
} else {
var culture = $.cookie('culture');
$("#selectLang").val(culture)
}
}
/** 變更語系*/
function changeLanguage() {
var selectedLang = $("#selectLang").val();
const urlParams = new URLSearchParams(window.location.search);
var param = urlParams.get('culture')
var pathName = $(location).attr('pathname');
console.log('changeLanguage urlParams:' + urlParams)
console.log('changeLanguage param:' + param)
console.log('changeLanguage pathname:' + pathName)
var url = pathName + "?culture=" + selectedLang;
window.location.href = url;
}
7.在Razor套用語系的寫法:
- 第一種
HomeController.cs
Index.cshtmlpublic IActionResult Index(string culture) { ViewData["Login"] = _localizer["Login"]; return View(); }
<h5>@ViewData["Login"]</h5>
- 第二種
Index.cshtml@using Microsoft.AspNetCore.Mvc.Localization @using Localization @inject IHtmlLocalizer<SharedResources> _localizer
畫面結果如下:<h5>@_localizer["lang"]</h5>