新文章 网摘 文章 随笔 日记

对用于参数名称、输入验证消息等的数据注释的多语言支持

Table of contents
Publish a set of files
https://github.com/onodera-sf/AspNetCoreLocalizationDataAnnotation

environment

ASP.NET Core
  • 5.0 MVC

premise

This Tips is written as understanding the following tips:

Also, if you are creating a new project, you must have added the following files and code based on tips above.

  • Create a SharedResource.resx (+en, es) file. (The contents may be empty.)
  • Create a SharedResource.cs file
  • Add localization code to Startup.ConfigureServices
  • Add localization code to Startup.Configure

Startup .cs Fixes

Because additional multilingual settings related to DataAnnotations are required, modify the method as follows:Startup.ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
  services.AddControllersWithViews();

  services.AddMvc()
    // ローカライズに必要。Resx ファイルのフォルダパスを指定
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; })
    // DataAnnotations のローカライズに必要 (追加)
    .AddDataAnnotationsLocalization(options =>
     {
       // DataAnnotation を使ったときのメッセージは SharedResource に集約する
       options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource));
     });
}

Modeling for input

Create a model to bind to the input screen. In this sample, we have created a number of properties to accommodate various input controls. If you're having trouble creating, you can just create two.

Create a UserViewModel .cs in the Models folder.

The code should look like this: The namespace should be appropriate. The attributes you set are not very relevant to multiple languages because they are only assigned to them. Multilingual support will be done later.

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace LocalizationDataAnnotation.Models
{
  public class UserViewModel
  {
    [Required]
    [Display(Name = "ID (半角英数字)")]
    [StringLength(20)]
    [RegularExpression(@"^[0-9a-zA-Z]*$")]
    public string ID { get; set; }

    [StringLength(50)]
    public string Name { get; set; }

    [StringLength(50, MinimumLength = 8)]
    [DataType(DataType.Password)]
    [RegularExpression(@"^[0-9a-zA-Z]*$", ErrorMessage = "Password")]
    public string Password { get; set; }

    // 省略
  }

  // 省略
}

Create an action

Create actions in to display the user's registration screen and perform registration actions.HomeController

Creating screens and actions is not the main subject of this Tips, so it is appropriate. In addition, the actual registration process is not performed.

// 初期コードは省略

namespace LocalizationDataAnnotation.Controllers
{
  public class HomeController : Controller
  {
    // 初期コードは省略

    public IActionResult Create()
    {
      return View();
    }

    [HttpPost]
    public IActionResult Create(UserViewModel model)
    {
      // エラーなら差し戻し
      if (ModelState.IsValid == false) return View(model);

      // 正常に登録できた場合は Index に戻る
      return RedirectToAction(nameof(Index));
    }
  }
}

Link to user registration screen

Create a link to the user registration screen in Views\Home\Index.cshtml. You can write anything as long as you can have a screen transition.

asp-route-culture The attribute opens the page in the specified language.

<!-- 初期コード省略 -->

<ul>
  <li><a asp-action="Create">Create</a></li>
  <li><a asp-action="Create" asp-route-culture="ja">Create (ja)</a></li>
  <li><a asp-action="Create" asp-route-culture="en">Create (en)</a></li>
  <li><a asp-action="Create" asp-route-culture="es">Create (es)</a></li>
</ul>

Create a user registration screen

Create Right-click the action and select Add View.

Select Razor View.

Make the template "Create" and the model class "UserViewModel". If you're using the sample code, I've also included comments in the code. If you put certain attributes in a property, you will get an error when generating code in scaffolding. Please temporarily comment out before creating a view.UserViewModel

If you really get an error when you create it, create an empty Razor view and include the following code:

@model LocalizationDataAnnotation.Models.UserViewModel
@using System.Globalization;
@{
  ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>UserViewModel</h4>
<hr />
<div class="row">
  <div class="col-md-4">
    <form asp-action="Create">
      <div asp-validation-summary="ModelOnly" class="text-danger"></div>
      <div class="form-group">
        <label asp-for="ID" class="control-label"></label>
        <input asp-for="ID" class="form-control" />
        <span asp-validation-for="ID" class="text-danger"></span>
      </div>
      <div class="form-group">
        <label asp-for="Name" class="control-label"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
      </div>
      <div class="form-group">
        <label asp-for="Password" class="control-label"></label>
        <input asp-for="Password" class="form-control" />
        <span asp-validation-for="Password" class="text-danger"></span>
      </div>

      <!-- 省略 -->

      <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" asp-route-culture="@CultureInfo.CurrentCulture.Name" />
      </div>
    </form>
  </div>
</div>

<div>
  <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
  @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

For now, as a preparatory stage, you can build the code so far successfully, and try to see and run the screen correctly.

Multilingual text registration for DataAnnotations

All properties are long to explain, so we'll talk to and for . Other properties are multilingual in a similar way, so try them out.IDName

The following texts are available in multiple languages here.

Multi-lingual textkeys
Id parameter display name ID_DisplayName
Error message when ID not entered Validate_Required
Error message when id input character exceeds 20 characters Validate_StringLength
Error message when id is typed with nonnumeric characters Validate_Alphanumeric
Name parameter display name Name_DisplayName
Error message when name has more than 50 characters entered Validate_StringLength

Validate_XXXXX be universal. There is no key naming convention, so you can freely attach it.

Using these keys as the basis, we will fill in the translated text into , , .SharedResource.resxSharedResource.en.resxSharedResource.es.resx

SharedResource.resx

Namevalue
Validate_Required "{0}" is required.
Validate_StringLength You can enter up to "{1}" in "{0}".
Validate_Alphanumeric {0} can only be alphanumeric.
ID_DisplayName ID (alphanumeric)
Name_DisplayName identity

SharedResource.en.resx

Namevalue
Validate_Required "{0}" is a required input.
Validate_StringLength The maximum number of characters that can be entered in "{0}" is "{1}".
Validate_Alphanumeric Only alphanumeric characters can be entered for "{0}".
ID_DisplayName ID (alphanumeric characters)
Name_DisplayName Full name

SharedResource.es.resx

Namevalue
Validate_Required "{0}" es una entrada obligatoria.
Validate_StringLength El número máximo de caracteres que se pueden ingresar en "{0}" es "{1}".
Validate_Alphanumeric Solo se pueden ingresar caracteres alfanuméricos para "{0}".
ID_DisplayName ID (caracteres alfanuméricos)
Name_DisplayName Nombre completo

Input validation error messages replace parameter names and numbers with {0} and {1}. Let's use it positively.

Multi-lingual application to DataAnnotations

All multilingual settings are applied to the attributes of the model (DataAnnotations).

To apply it to the display name of the parameter, attach and specify a sharedResource.resx key in the property.DisplayName

To apply to error messages during input validation, specify a sharedResource.resx key in the property of each validation attribute.ErrorMessage

public class UserViewModel
{
  [Required(ErrorMessage = "Validate_Required")]
  [Display(Name = "ID_DisplayName")]
  [StringLength(20, ErrorMessage = "Validate_StringLength")]
  [RegularExpression(@"^[0-9a-zA-Z]*$", ErrorMessage = "Validate_Alphanumeric")]
  public string ID { get; set; }

  [Display(Name = "Name_DisplayName")]
  [StringLength(50, ErrorMessage = "Validate_StringLength")]
  public string Name { get; set; }

  // 省略
}

This completes the setup. After that, run it to see how it works.

By the way, the number of input characters is limited by the attribute of the input tag. If you want to see the message, you need to remove the restrictions, such as in the developer tools of your Web browser.maxlength

By the way, there are some messages displayed when registering your age, date, etc. empty. This is a message that is set up on the framework side, but another Tips will show you how to support it in multiple languages.

For all codes

This Tips contains only some properties, but the sample code covers all html5-enabled input fields. If you want to check, please refer to the link above the page.

Listed in part below

 

 

 

posted @ 2022-09-02 19:55  岭南春  阅读(53)  评论(0)    收藏  举报