如何为ASP.Net Core 3.1的Ajax custom.js文件设置本地化?
Got it, let's tackle how to localize that "Copy" text in your custom.js file since you're already set up with ASP.NET Core Localization and .resx files. Here are three practical, straightforward approaches you can use:
Approach 1: Inject Localized Text as Global Variables (Simplest)
This is the most direct method—you'll pass the localized values from your .resx files to the frontend via a global JavaScript object in your view.
- In your view (e.g.,
_Layout.cshtmlor the specific page where your JS runs), inject the string localizer:
@inject IStringLocalizer<YourResourceClassName> Localizer
Replace YourResourceClassName with the actual class name tied to your .resx files (usually the name of the resource file without the culture suffix, like SharedResources).
- Add a script block to define the global variable with your localized text:
<script> // Use Json.Serialize to safely handle special characters in localized text window.localizedStrings = { copyLabel: @Json.Serialize(Localizer["Copy"]) }; </script>
Make sure this script loads before your custom.js file so the variable is available when the JS runs.
- Update your
custom.jsto use the global variable instead of hardcoded text:
$('.copy-gbt-to-clipboard').on("click", function () { var rowNumber = $(this).data('rownumber'); var clickedElementID = rowNumber; var Value = $(clickedElementID).text(); var $temp = $("<input>"); $("body").append($temp); $temp.val(Value).select(); // Replace hardcoded "Copy" with the localized value $(clickedElementID_Value).append('<span class=" tooltiptext-selector_' + rowNumber + '">' + window.localizedStrings.copyLabel + '</span>'); });
Approach 2: Embed Localized Text in Element Data Attributes
If you prefer not to use global variables, you can attach the localized text directly to the clickable element as a data attribute.
- When rendering your
.copy-gbt-to-clipboardelements in the view, add adata-copy-textattribute with the localized value:
<button class="copy-gbt-to-clipboard" data-rownumber="your-row-id" data-copy-text="@Localizer["Copy"]"> <!-- Your button content --> </button>
- Modify your
custom.jsto read this data attribute when the button is clicked:
$('.copy-gbt-to-clipboard').on("click", function () { var rowNumber = $(this).data('rownumber'); // Get the localized text directly from the button's data attribute var copyText = $(this).data('copy-text'); var clickedElementID = rowNumber; var Value = $(clickedElementID).text(); var $temp = $("<input>"); $("body").append($temp); $temp.val(Value).select(); $(clickedElementID_Value).append('<span class=" tooltiptext-selector_' + rowNumber + '">' + copyText + '</span>'); });
This keeps your JS clean and avoids global scope pollution.
Approach 3: Fetch Localized Text via AJAX (For Dynamic Language Switching)
If you need to support switching languages without reloading the page, you can create a simple API endpoint to retrieve localized text on demand.
- Create an API controller to handle localization requests:
[ApiController] [Route("api/localization")] public class LocalizationController : ControllerBase { private readonly IStringLocalizer<YourResourceClassName> _localizer; public LocalizationController(IStringLocalizer<YourResourceClassName> localizer) { _localizer = localizer; } [HttpGet("{key}")] public IActionResult GetLocalizedText(string key) { var localizedText = _localizer[key]; return Ok(localizedText.Value); } }
- Update your
custom.jsto fetch the text via AJAX when the button is clicked:
$('.copy-gbt-to-clipboard').on("click", function () { var rowNumber = $(this).data('rownumber'); var clickedElementID = rowNumber; var Value = $(clickedElementID).text(); var $temp = $("<input>"); $("body").append($temp); $temp.val(Value).select(); // Fetch localized text from the API $.get('/api/localization/Copy', function(localizedText) { $(clickedElementID_Value).append('<span class=" tooltiptext-selector_' + rowNumber + '">' + localizedText + '</span>'); }); });
Note: This adds an extra network request, so only use this if you need dynamic language switching without page reloads.
My recommendation? Go with Approach 1 or 2 for most cases—they're lightweight, easy to implement, and play nicely with your existing .resx setup.
内容的提问来源于stack exchange,提问作者IMCartman

