使用DataTables.net的ASP.NET8——第4部分——多语言

82 篇文章 3 订阅

目录

1使用jQuery DataTables.net的ASP.NET8

1.1 本系列中的文章

2 最终结果

3 多语言设置

4 客户端DataTables.net组件

5 总结

6 参考资料


1使用jQuery DataTables.netASP.NET8

我正在评估jQuery datatable.net组件[1]ASP.NET8项目中的使用,并创建了几个原型(概念验证)应用程序,这些应用程序将在这些文章中展示。

1.1 本系列中的文章

本系列中的文章包括: 

2 最终结果

本文的目标是创建一个概念验证应用程序,该应用程序ASP.NET多语言应用程序中演示DataTables.net组件。让我们介绍一下这篇文章的结果。

以下是英文版本

这是德语版本

因此,DataTables.net组件都可以在多语言应用程序中使用。请注意,我们需要在两个级别上设置翻译:

  1. DataTables.net组件本身的翻译
  2. DataTables.net组件使用的字符串的翻译

正确设置它有点棘手,但这是可行的。

3 多语言设置

如果你不熟悉ASP.NET8的多语言设置,请阅读我的文章[2]-[5]。我不打算在这里再次复制粘贴相同的文本,我将在这里使用这些示例中的相同代码。如这些文章中所述,主要技巧是为特定语言正确设置AspNetCore.Culture Cookie。这些文章[2]-[5]中详细解释了所有内容。

以下是执行此操作的控制器代码:

//HomeController.cs

 public IActionResult ChangeLanguage(ChangeLanguageViewModel model)
{
    if (model.IsSubmit)
    {
        HttpContext myContext = this.HttpContext;
        ChangeLanguage_SetCookie(myContext, model.SelectedLanguage);
        //doing funny redirect to get new Request Cookie
        //for presentation
        return LocalRedirect("/Home/ChangeLanguage");
    }

    //prepare presentation
    ChangeLanguage_PreparePresentation(model);
    return View(model);
}

private void ChangeLanguage_PreparePresentation(ChangeLanguageViewModel model)
{
    model.ListOfLanguages = new List<SelectListItem>
                {
                    new SelectListItem
                    {
                        Text = "English",
                        Value = "en"
                    },

                    new SelectListItem
                    {
                        Text = "German",
                        Value = "de",
                    },

                    new SelectListItem
                    {
                        Text = "French",
                        Value = "fr"
                    },

                    new SelectListItem
                    {
                        Text = "Italian",
                        Value = "it"
                    }
                };
}

private void ChangeLanguage_SetCookie(HttpContext myContext, string? culture)
{
    if (culture == null) { throw new Exception("culture == null"); };

    //this code sets .AspNetCore.Culture cookie
    CookieOptions cookieOptions = new CookieOptions();
    cookieOptions.Expires = DateTimeOffset.UtcNow.AddMonths(1);
    cookieOptions.IsEssential = true;

    myContext.Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        cookieOptions
    );
}

下面是我用于调试目的的视图中的页脚

@* _Debug.AspNetCore.CultureCookie.cshtml ===================================================*@
@using Microsoft.AspNetCore.Localization;

@{
    string text = String.Empty;

    try
    {
        var myContext = Context;
        string? cultureCookieValue = null;
        myContext.Request.Cookies.TryGetValue(
            CookieRequestCultureProvider.DefaultCookieName, out cultureCookieValue);
        string? text1 = "Request Cookie was (Refresh might be needed if changing language) " +
            CookieRequestCultureProvider.DefaultCookieName + "[" + cultureCookieValue + "]";

        text = text1;
    }
    catch (Exception ex)
    {
        text = ex.Message;
    }

    <span>
        @text
    </span>
}

以下是DataTables.net组件本身的翻译

以下是应用程序中字符串的翻译

4 客户端DataTables.net组件

在这里,我将只展示使用DataTables组件的ASP.NET视图是什么样子的。

<!-- Employees.cshtml -->
<partial name="_LoadingDatatablesJsAndCss" />

@{
    <div class="text-center">
        <h3 class="display-4">Employees table</h3>
    </div>

    <!-- Here is our table HTML element defined. JavaScript library Datatables
    will do all the magic to turn it into interactive component -->
    <table id="EmployeesTable01" class="table table-striped table-bordered ">
    </table>
}

@{
    <!-- Method to tell DatTables.net component which 
    language file to load -->
    string GetUrlForDatatablesLanguageFile()
    {
        string urlResult = String.Empty;

        try
        {
            string culture = Thread.CurrentThread.CurrentUICulture.ToString();

            if (culture.Length > 2)
            {
                culture = culture.Substring(0, 2).ToLower();
            }

            string baseUrl = Url.Content("~/lib/datatables/i18n/");

            switch (culture)
            {
                case "de":
                    urlResult = baseUrl + "de-DE.json";
                    break;
                case "fr":
                    urlResult = baseUrl + "fr-FR.json";
                    break;
                case "it":
                    urlResult = baseUrl + "it-IT.json";
                    break;
                default:
                    urlResult = String.Empty;
                    break;
            }
        }
        catch
        {
            urlResult = String.Empty;
        }

        return urlResult;
    }
}

<script>
    // Datatables script initialization=========================================
    // we used defer attribute on jQuery so it might not be available at this point
    // so we go for vanilla JS event

    document.addEventListener("DOMContentLoaded", InitializeDatatable);

    function InitializeDatatable() {
        $("#EmployeesTable01").dataTable({
            //processing-Feature control the processing indicator.
            processing: true,
            //paging-Enable or disable table pagination.
            paging: true,
            //info-Feature control table information display field
            info: true,
            //ordering-Feature control ordering (sorting) abilities in DataTables.
            ordering: true,
            //searching-Feature control search (filtering) abilities
            searching: true,
            //search.return-Enable / disable DataTables' search on return.
            search: {
                return: true
            },
            //autoWidth-Feature control DataTables' smart column width handling.
            autoWidth: true,
            //lengthMenu-Change the options in the page length select list.
            lengthMenu: [10, 15, 25, 50, 100],
            //pageLength-Change the initial page length (number of rows per page)
            pageLength: 10,

            //order-Initial order (sort) to apply to the table.
            order: [[1, 'asc']],

            //serverSide-Feature control DataTables' server-side processing mode.
            serverSide: true,

            //stateSave-State saving - restore table state on page reload.
            stateSave: true,
            //stateDuration-Saved state validity duration.
            //-1 sessionStorage will be used, while for 0 or greater localStorage will be used.
            stateDuration: -1,

            //language.url- Load language information from remote file.
            language: {
                url: '@GetUrlForDatatablesLanguageFile()'
            },

            //Load data for the table's content from an Ajax source.
            ajax: {
                "url": "@Url.Action("EmployeesDT", "Home")",
                "type": "POST",
                "datatype": "json"
            },

            //Set column specific initialization properties
            columns: [
                //name-Set a descriptive name for a column
                //data-Set the data source for the column from the rows data object / array
                //title-Set the column title
                //orderable-Enable or disable ordering on this column
                //searchable-Enable or disable search on the data in this column
                //type-Set the column type - used for filtering and sorting string processing
                //visible-Enable or disable the display of this column.
                //width-Column width assignment.
                //render-Render (process) the data for use in the table.
                //className-Class to assign to each cell in the column.

                {   //0
                    name: 'id',
                    data: 'id',
                    title: "@Example04.Resources.SharedResource.EmployeeId",
                    orderable: true,
                    searchable: false,
                    type: 'num',
                    visible: true
                },
                {
                    //1
                    name: 'givenName',
                    data: "givenName",
                    title: "@Example04.Resources.SharedResource.GivenName",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //2
                    name: 'familyName',
                    data: "familyName",
                    title: "@Example04.Resources.SharedResource.FamilyName",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //3
                    name: 'town',
                    data: "town",
                    title: "@Example04.Resources.SharedResource.Town",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //4
                    name: 'country',
                    data: "country",
                    title: "@Example04.Resources.SharedResource.Country",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true,
                    width: "150px",
                    className: 'text-center '
                },
                {
                    //5
                    name: 'email',
                    data: "email",
                    title: "@Example04.Resources.SharedResource.Email",
                    orderable: true,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //6
                    name: 'phoneNo',
                    data: "phoneNo",
                    title: "@Example04.Resources.SharedResource.PhoneNumber",
                    orderable: false,
                    searchable: true,
                    type: 'string',
                    visible: true
                },
                {
                    //7
                    name: 'actions',
                    data: "actions",
                    title: "@Example04.Resources.SharedResource.Actions",
                    orderable: false,
                    searchable: false,
                    type: 'string',
                    visible: true,
                    render: renderActions
                },
                {
                    //8
                    name: 'urlForEdit',
                    data: "urlForEdit",
                    title: "urlForEdit",
                    orderable: false,
                    searchable: false,
                    type: 'string',
                    visible: false
                }
            ]
        });

        function renderActions(data, type, row, meta) {
            //for Edit button we get Url from the table data
            let html1 =
                '<a class="btn btn-info" href="' +
                row.urlForEdit +
                '"> @Example04.Resources.SharedResource.Edit</a>';

            //for Info button we create Url in JavaScript
            let editUrl = "@Url.Action("EmployeeInfo", "Home")" +
                "?EmployeeId=" + row.id;
            let html2 =
                '<a class="btn btn-info"  style="margin-left: 10px" href="' +
                editUrl + '"> @Example04.Resources.SharedResource.Info</a>';
            return html1 + html2;
        }
    }
</script>

请注意,我们需要在两个级别上设置翻译:

  1. DataTables.net组件本身的翻译
  2. DataTables.net组件使用的字符串的翻译

对于1),我们使用方法GetUrlForDatatablesLanguageFile()告诉组件要加载DatTables.net语言文件。

对于2)我们使用Resource Manager,如[5]中所述。

5 总结

可以下载完整的示例代码项目。

6 参考资料

[1] DataTables | Javascript table library

[2] ASP.NET 8——使用单个Resx文件的多语言应用程序

[3] ASP.NET 8——使用单个Resx文件的多语言应用程序——第2部分——替代方法

[4] ASP.NET 8——使用单个Resx文件的多语言应用程序——第3部分——表单验证字符串

[5] ASP.NET 8——使用单个Resx文件的多语言应用程序——第4部分——资源管理器

https://www.codeproject.com/Articles/5385407/ASP-NET8-using-DataTables-net-Part4-Multilingual

基于STM32F407,使用DFS算法实现最短迷宫路径检索,分为三种模式:1.DEBUG模式,2. 训练模式,3. 主程序模式 ,DEBUG模式主要分析bug,测量必要数据,训练模式用于DFS算法训练最短路径,并将最短路径以链表形式存储Flash, 主程序模式从Flash中….zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值